Home  >  Article  >  Web Front-end  >  JQuery raises $(document.ready) event twice_jquery

JQuery raises $(document.ready) event twice_jquery

WBOY
WBOYOriginal
2016-05-16 18:36:26806browse

The page probably looks like this, a Partial View, and this View contains a small piece of Javascript bound to Search, and is included in the Jquery-ui dialog. And it is definitely not a problem with ASP.net mvc generating HTML. The HTML is based on my idea. Generated, but there was really no way to do it. I removed the dialog code and the Search button became normal. I checked the dialog code and found that it was caused by appendTo.
I did an experiment and the code is as follows:
Code

Copy the code The code is as follows:










It is expected that alert('a1') should be executed once, but due to the use of appendTo, it is executed twice. Regardless of whether you use $(document).ready in the a1 div, javascript will be run twice. The first The document loading was completed for the first time, and appendTo was called for the second time.

First, it was changed to the following method, which failed.
Code
Copy code The code is as follows:





Change it to the following and you will be successful.
Copy code The code is as follows:

var loaded = false;
$(document) .ready(function() {
if (!loaded) {
alert('a1');
loaded = true;
}
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn