如何清除被设置为通过jQuery document.ready()
调用触发的匿名函数?
例如:
<script type="text/javascript">
//some code sets a doc ready callback
$(document).ready(function ()
{
alert('ready');
});
//my attempt to prevent the callback from happening
window.onload = null;
$(document).unbind("ready");
</script>
无论我如何尝试绕过它,警报都会发生。有没有办法做到这一点?
发布于 2011-10-18 22:19:56
如果你描述了你真正想要解决的问题,你可能会得到最合适的答案。
jQuery没有公开记录的方法来撤消或阻止document.ready()处理程序。如果您控制代码,则可以使用全局变量和条件,如下所示:
var skipReady = false;
$(document).ready(function ()
{
if (!skipReady) {
alert('ready');
}
});
// skip the document.ready code, if it hasn't already fired
skipReady = true;
或者,如果您想深入了解一下jQuery (除了文档介绍的接口之外),您可以这样做:
$(document).ready(function() {
alert("ready");
});
// stop the ready handler
$.isReady = true;
你可以在这里看到最后一个:http://jsfiddle.net/jfriend00/ZjH2k/。这之所以有效,是因为jQuery使用属性:$.isReady
来跟踪它是否已经触发了就绪处理程序。将它设置为true会使它认为它已经解雇了他们,所以它不会每次都这样做。
发布于 2011-10-18 22:20:50
这是可行的:
$(document).bind("ready", function () { alert("hey!"); });
$(document).unbind("ready");
在我看来,这是一个bug -- jQuery中的所有其他事件都可以解除绑定。省略这一点是不一致的。
没有直接回答遗漏的问题,但这里有一些来自jQuery docs的相关信息
以下三种语法都是等效的:
$(document).ready(handler)
$().ready(handler)
(这不是recommended)$(handler)
还有$(document).bind("ready", handler)
。它的行为类似于ready方法,但有一个例外:如果ready事件已经激发,并且您试图执行.bind("ready")
,则不会执行绑定的处理程序。以这种方式绑定的就绪处理程序将在上面其他三个方法的任何绑定之后执行。
发布于 2011-10-18 22:17:27
$(document).ready()依赖于由浏览器触发的onLoad事件,这意味着您无法阻止它的发生。如果alert()是由某种条件决定的,那么我将使用if/else语句来决定是否调用它。
https://stackoverflow.com/questions/7814408
复制相似问题