我想這樣做:如果jQuery不存在,請添加jQuery dinamically並使用alert來測試它。但這不起作用,「我做錯了什麼?如何將JavaScript動態添加到HTML並正確加載它?
HMTL:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml" id="crishk">
<head>
</head>
<body>
Welcome to Javascript Loader</a>
<div id="alertme">Alert me!</div>
<script type="text/javascript" language="javascript" src="dynamic.js"></script>
</body>
</html>
文件dynamic.js
if (typeof jQuery == 'undefined') {
alert('You need to install jQuery to proceed.!');
var oHead = document.getElementsByTagName('head').item(0);
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js";
oHead.appendChild(oScript);
} else {
alert('jQuery is present...');
}
$(document).ready(function() {
alert($('#alertme').html());
});
但是,你應該在你的HTML載入的jQuery。用戶不需要加載它。 。 。 – 2013-02-09 05:29:42
爲什麼要動態添加JQuery? – 2013-02-09 05:29:47
在調用'$(document).ready(...)'之前,jquery API的負載不會發生,因爲'$'還沒有被定義。 – 2013-02-09 05:30:13