多个 $(document).ready(function(){})
我最近开始使用 jQuery 工作,现在当我正在开发一个项目时,我使用 ajax 函数并一次又一次加载相同的库(我已经编写)。由于 $(document).ready(function(){})
一次又一次地调用。意味着如果我一次又一次地加载 4 次,一个函数会调用 4 次。
我想清理/未准备/卸载以前准备好的功能,并想准备好新功能。我也经常尝试 $(function(){})
。但结果相同。我试图获取任何相应/相关的主题。但无法找到。
如果我找不到这个或没有人可以帮助我。那么我想我应该将我的一个库拆分/分解为多个库。
I have recently started working in jQuery and now when i am working on an project where i am using ajax function and loading the same library(i have written) again and again. and due to that $(document).ready(function(){})
calls again and again. Means one function calls for 4 time if i use to load it 4 times again and again.
I want to clean/unready/unload previous ready function and want to ready new function . i use to try on $(function(){})
also. but the same result. i tried to get any respective/ related topic. but couldn't find out.
If i could not find this or no one can help me. then i think i should have to split/break my one library to numbers of libraries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这按预期工作,多个事件注册将彼此独立地触发。
不过,您可以采取解决方法:设置一个标志,如果多次调用,该标志将阻止执行。例如,此页面将加载您的脚本四次,但事件注册只会发生一次:
然后,在 yourscript.js 中:
请注意,将您的库拆分为只需要一次的部分和将其拆分为需要的部分可能会更容易被重复调用,并且只加载初始部分一次。
That works as intended, multiple event registrations will fire independently of each other.
You could make a workaround, though: set a flag that will prevent execution if called more than once. For example, this page would load your script four times, but the event registration would only happen once:
Then, in yourscript.js:
Note that it might be easier to split your library into the part that is only needed once and into the part that is called repeatedly, and only load that initial part once.