简体   繁体   English

jQuery和document.ready()触发两次

[英]jQuery and document.ready() firing twice

I know it is quite a common issue, but even with research I was not able to understand what goes wrong in my call to document.ready() Javascript function. 我知道这是一个很普遍的问题,但是即使进行研究,我也无法理解调用document.ready()Javascript函数时出了什么问题。

For some reason, it gets called twice, even when I don't execute anything else than an alert. 由于某种原因,即使我没有执行警报以外,它也被调用两次。

As I said in the title, I am using jQuery, and figured something could come from $(function(){}), so I removed any execution in there as well. 就像我在标题中说的那样,我使用的是jQuery,并认为$(function(){})可能会带来一些问题,因此我也删除了其中的所有执行。 Nothing changes, document.ready() is still called twice. 不变,document.ready()仍被调用两次。

What can be the origin of this issue? 这个问题的根源是什么? How to troubleshoot/solve it? 如何解决/解决它?

Thanks in advance! 提前致谢!

Here's the code I've tried : 这是我尝试过的代码:

$(function(){
    //$( "#tabs" ).tabs();
});

$(document).ready(function() {
    //getTableEntity("organisation", "getentitytable", "#testtable");
    //standardDataTable('#tableOrga');
    alert("document.ready");
});

Edit : I know I'm using the same function twice. 编辑:我知道我两次使用相同的功能。 Putting everything in one function doesn't solve the problem. 将所有内容放在一个函数中并不能解决问题。

Do you use a template-Engine such smarty or .net or something else? 您是否使用诸如smarty或.net之类的模板引擎? It could be that there is a double script source for jquery. 可能是jquery有双重脚本源。 Then there are side effects. 然后有副作用。

You can check if the dom is ready with this code. 您可以使用此代码检查dom是否准备就绪。 Place code in your javascript source file. 将代码放在您的javascript源文件中。

// If the DOM is already ready
if ( jQuery.isReady ) {
// Execute the function immediately
fn.call( document, jQuery );
} // ...

should use one of them... and put your code on one of the following jquery function 应该使用其中之一...并将您的代码放在以下jquery函数之一上

$(function(){
    //$( "#tabs" ).tabs();
});

OR 要么

$(document).ready(function() {
    //getTableEntity("organisation", "getentitytable", "#testtable");
    //standardDataTable('#tableOrga');
    alert("document.ready");
});

$(function(){ is equal to $(document.ready) $(function(){等于$(document.ready)

Read here on jquery jQuery上阅读

i think this demo will help you 我认为这个演示会帮助您

<script>
    $(function(){
        $('#test1').appendTo('#test2');
        console.log(1);
    })
</script>
<div id="test1">
<script>
    $(function(){
        console.log(2);     
    });
</script>
</div>

<div id="test2"></div>

the console.log(2) will fire twice. console.log(2)将触发两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM