JQuery raises two $ (document. ready) Events

Source: Internet
Author: User

The page is probably like this, a Partial View, which contains a small section of Javascript bound to Search, which is included in the Jquery-ui dialog, it is also determined that it is not the problem of ASP.net mvc generating HTML. HTML is generated according to my idea. There is no way to remove the dialog code and the Search will work normally. I checked the dialog code and found that it was caused by appendTo.
The Code is as follows:
Code
Copy codeThe Code is as follows:
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ("# A1"). appendTo ($ ("# a2 "));
});
</Script>

<Div id = "a1">
<Script type = "text/javascript">
Alert ('a1 ');
</Script>
</Div>

<Div id = "a2">
</Div>

It is expected that alert ('a1') should be executed once, but because appendTo is used, it is executed twice, no matter whether you use $ (document) in the a1 div ). ready will run javascript twice. The first time the document is loaded, the second time it is called appendTo.

First, change to the following method.
Code
Copy codeThe Code is as follows:
<Div id = "a1">
<Script type = "text/javascript">
Loaded = false;
If (loaded = false ){
Alert ('a1 ');
Loaded = true;
}
</Script>
</Div>

Then change it to the following, and you will be able to succeed.
Copy codeThe Code is as follows:
Var loaded = false;
$ (Document). ready (function (){
If (! Loaded ){
Alert ('a1 ');
Loaded = true;
}
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.