[英]Handling multiple document ready event listeners
我的代码中有多个文档就绪事件监听器。
$(document).ready(function() {
console.log("hello james")
});
$(document).ready(function() {
console.log("hello cindy")
});
$(document).ready(function() {
console.log("hello dave")
});
我只希望在用户访问页面时准备好调用第一个文档。 我不需要其他两个文档准备调用。
我不能使用全局变量来检查这一点。 我希望做的是使用bind
。 我的理论是通过将代码设置为...
$(document).bind("ready", function() {
console.log("hello james")
});
$(document).bind("ready", function() {
console.log("hello cindy")
});
$(document).bind("ready", function() {
console.log("hello dave")
});
只有第一个绑定会调用。 这就是我目前对bind
如何工作的理解。
现在,这里是踢腿者。 我需要做的是,一旦这些绑定运行(再次,我只希望第一个绑定被执行,从而在控制台日志中打印出“ hello james”),我就需要取消准备就绪的文档的绑定。 我在想做...
$(document).bind("ready", function() {
console.log("hello james")
$(document).unbind("ready");
});
$(document).bind("ready", function() {
console.log("hello cindy")
});
$(document).bind("ready", function() {
console.log("hello dave")
});
但这不起作用。 “ hello james”将被记录,但ready事件不会解除绑定。 我在这里想念什么吗? 我究竟做错了什么?
您可以尝试event.stopImmediatePropagation()
。
这可以防止执行绑定到同一事件的任何其他处理程序:
$(document).on("ready",function(e) { e.stopImmediatePropagation(); console.log("hello james"); }); $(document).on("ready",function(){console.log("hello cindy");}); $(document).on("ready",function(){console.log("hello dave");});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
(我将.ready(
更改为.on("ready",
因为否则代码段和jsfiddle都将无法工作/不会产生错误,尽管我不明白为什么。据我所知, .ready(
应该可以正好。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.