我不知道我的代码出了什么问题。如果页面上不存在jQuery,我会尝试动态加载它。
<head>
<script>
(function() {
if (typeof jQuery != 'undefined') {
/* jQuery is already loaded... verify minimum version number of 1.4.2 and reload newer if needed */
if (/1\.(0|1|2|3|4)\.(0|1)/.test(jQuery.fn.jquery) || /^1.1/.test(jQuery.fn.jquery) || /^1.2/.test(jQuery.fn.jquery)|| /^1.3/.test(jQuery.fn.jquery)) {
loadJQ();
}
} else {
loadJQ();
}
function loadJQ() {
/* adds a link to jQuery to the head, instead of inline, so it validates */
var headElement = document.getElementsByTagName("head")[0];
linkElement=document.createElement("script");
linkElement.src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
linkElement.type="text/javascript";
headElement.appendChild(linkElement);
//alert(headElement);
}
})();
</script>
</head>这是我的身体。
<body>
<button>Click me</button>
<script type="text/javascript">
$(document).ready(function(){
alert("hello");
$("button").click(function(){
$(this).hide();
});
});
</script>
</body>当我把它放到一个html页面中时,我得到了一个错误,说"$ is not defined“。有人知道为什么吗?
发布于 2012-01-12 03:46:02
在一个朋友的帮助下,我找到了上面代码的问题所在。
当document.ready运行时,jquery不在页面上(有两个onReady元素在运行)…由于addToHead版本是非阻塞的,因此javascript的其余部分将并行执行并失败。
我在body标签开始之后添加了这个,它工作得很好:
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write('<scr'+'ipt type="text/javascript" src="http://ajax.googleapis.com /ajax/libs/jquery/1.7.1/jquery.min.js">'+'</scr'+'ipt>');
}
</script>发布于 2012-01-07 03:54:44
"$ is not defined“错误表示jquery未加载。
尝试使用此脚本加载jquery。
http://css-tricks.com/snippets/jquery/load-jquery-only-if-not-present/
发布于 2012-01-07 03:56:49
"$ is not defined“错误是由于脚本尝试执行时未下载jQuery代码而导致的。
您可以尝试使用脚本属性defer来延迟代码的执行,直到加载代码为止,方法是将脚本标记更改为
<script type="text/javascript" defer="defer">https://stackoverflow.com/questions/8763580
复制相似问题