如何检查我的文档是否只有一个$(document).ready(function()实例
如果它被多次包含,我能以某种方式删除重复的实例(类似于PHP的require_once();函数)吗?
发布于 2011-02-22 02:05:24
您是说完全相同的代码可以添加多次吗?
如果是这样,我想您可以设置一个全局属性来指示内部代码是否已经运行,然后在ready()处理程序中测试该属性。
$(document).ready(function() {
// check a flag to see if this has been called yet
if( !window.thisCodeHasRun ) {
// set the flag to show this has been called
window.thisCodeHasRun = true;
/* run your code */
}
});最好在服务器端处理这一点,但如果您必须在客户端做这件事,这应该是可行的。
发布于 2011-02-22 02:11:47
一种选择是使用绑定和解除绑定:
$(document).bind("ready",function(){
console.log("zero");
});
$(document).bind("ready",function(){
console.log("one");
});
// get rid of previous ready events
$(document).unbind("ready");
$(document).bind("ready",function(){
console.log("two");
});在上面的代码中,第一个和第二个ready事件将永远不会触发,因为已经调用了unbind。因此,您将在控制台中获得"two“。
https://stackoverflow.com/questions/5069139
复制相似问题