jquery binding events are not effective solutions _jquery

Source: Internet
Author: User
The jquery binding Click event was discovered today when the front page was developed. The code is as follows:
1.html:<input id= "ceshisub" type= "button" value= "click event" >
The method function in the test.js referenced by 2.html:
Copy Code code as follows:

$ ("#ceshisub"). Bind ("click", Function () {
var a=1;
a +=1;
Alert ("Ceshisub");
});

The problem is to solve the "click event" button in the page without any response, open the JS Debugging window in Var a=1; The breakpoint in this line is not coming in.
The solution is:
First, add the loading event on the JS function above:
The following code is added:
Copy Code code as follows:

$ (function () {
$ ("#ceshisub"). Bind ("click", Function () {
var a=1;
a +=1;
Alert ("Ceshisub");
});
});

In this case, the binding event takes effect.
JS has a total of three load functions, in addition to the above
Copy Code code as follows:

$ (function () {
Alert ("1th method. ");
});

There are two other ways to do this:
Copy Code code as follows:

Window.onload=function () {
Alert ("2nd method. ");
}

$ (document). Ready (function () {
Alert ("3rd method. ");
});

Second, if you do not use the JS load function to initialize the binding event, there is another way:
Statement that will refer to JS
<script language= "javascript" src= "/js/test.js" ></script>
Put it on the last side of the page to load.

Summarize:
jquery When you bind an event on an element, it first looks up the element A in docment, and the binding fails if it is not found.
The first solution above is to bind when initializing JS when the page is initialized
The second way is to ensure that the page elements are initialized after the completion of the binding, when all the elements have been initialized, must be bound.

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.