jQuery(document).ready()不触发

4

有人知道为什么jQuery文档准备就绪事件可能不会在网站上触发吗?我将这个脚本完全放在页脚,但它根本没有触发(jQuery 1.8已包含在head部分):

<script type="text/javascript">
jQuery(document).ready(function() { 
     alert('test');
     jQuery("#slideshow iframe").each(function(){ 
          alert('test');
     });
});
</script>

没有 JavaScript 错误,控制台为空,并且当我在 Firebug 的控制台中运行此代码时,它可以正常工作:

jQuery("#slideshow iframe").each(function(){ 
     alert('test');
});

是的,甚至没有第一次...我对此无解释。 - Atadj
1
你在其他地方之前调用了 jQuery(document).ready(function(){}); 吗? - Giona
1
根据你的描述,看起来很不错,但是听起来页脚中的脚本从未被执行。你能否为我们创建一个jsFiddle以尝试重现它? - jimp
我添加了网站地址。 - Atadj
1
@FrédéricHamidi:不一定是真的。如果处理程序抛出错误,进一步的处理程序可能不会被调用。 - Tgr
显示剩余9条评论
3个回答

5

虽然在这个具体的实例中并非如此,但一个非常烦人的情况是通过jQuery bug 10251发生:在$(document).ready()回调函数中出现错误会阻止所有在它之后注册的回调函数运行。(在这种情况下,可能会有JavaScript错误,尽管看起来与此无关。)


3
您当前在页面上遇到了以下错误:
Uncaught TypeError: Property '$' of object [object Window] is not a function 

这个错误的原因在于您的flow.anything-slider-1.0.js文件中的第11行。

该文件使用jQuery(document).ready(),所以$未定义。
将第11行从使用$更改为jQuery即可解决问题:
// doesn't work
$("#content").before("<div id=\"cycledump\"></div>");

// Does work
jQuery("#content").before("<div id=\"cycledump\"></div>");

整个文件使用jQuery而不是$,因此该文件应该坚持一种使用jQuery的方式,而不是混合使用。
编辑 我刚刚仔细检查了.ready()文档,下面的段落很有趣,因为它似乎与这个问题有关:

Aliasing the jQuery Namespace
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $.

However, the handler passed to the .ready() method can take an argument, which is passed to the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});
这意味着,你可以将第一行改为jQuery(document).ready(function($) {并将$作为参数传递,而不是修复第11行。这可能会使您能够在整个文件中使用$和jQuery。
无论如何,我不确定将$作为参数传递是否适用于您的情况,我只是想提及一下以防万一。

已解决 :) 多谢!我之前没注意到,因为Firebug没有显示错误...只有Chrome Developer Tools才显示了。 - Atadj
@Paul:那就是我一直在使用的,它确实帮助我准确定位了问题。 - Nope

1

这可能是jQuery库路径问题。尝试从jquery.com加载它 -

<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>

<script type="text/javascript">

$(document).ready(function() { 
     alert('test');
});

</script>

复制此代码并粘贴到部分

编辑:

您正在使用jQuery 1.4.21.8 jQuery UI

尝试将


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接