Home > Web Front-end > JS Tutorial > body text

Solution to jquery binding event not taking effect_jquery

WBOY
Release: 2016-05-16 17:00:35
Original
1847 people have browsed it

Today when I was developing the front page, I found that jquery bound click event did not take effect. The code is as follows:
1.html:
The method function in test.js referenced by 2.html:

Copy code The code is as follows:

$("#ceshisub").bind("click", function(){
var a=1;
a =1;
alert("ceshisub");
});

The problem is that the page There is no response when I try to solve the "Click Event" button. When I open the js debugging window, the breakpoint on the line var a=1; does not come in.
The solution is:
1. Add a loading event to the above js function:
The added code is as follows:
Copy code The code is as follows:

$(function(){
$("#ceshisub").bind("click",function(){
var a=1;
a =1;
alert("ceshisub");
});
});

In this case, the binding event will take effect .
There are three loading functions of js, in addition to the above-mentioned
Copy the code The code is as follows:

$(function(){
alert("Method 1.");
});

There are also the following two methods:
Copy code The code is as follows:

window.onload=function(){
alert("Method 2 . ");
}

$(document).ready(){
alert("Method 3.");
});

Second, if you do not use the js loading function to initialize the binding event, there is another method:
Reference the statement of js

is placed at the end of the page to load.

Summary:
When jquery binds an event on element A, it will first search for the element A in the document. If it is not found, the binding fails.
The first solution above is to bind when initializing js after the page is initialized
The second method is to ensure that all page elements are initialized before binding. At this time, all The elements have been initialized and can definitely be bound.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!