我想这样做:如果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