Jquery binding event does not take effect

  • 2020-03-30 01:40:25
  • OfStack

Today, when I was developing the foreground page, I found that jquery binds to the click event and nothing works. The code is as follows:
1. HTML: < Input id="ceshisub" type="button" value=" click event ">
2. Method function in test.js referenced by HTML:
 
$("#ceshisub").bind("click",function(){ 
var a=1; 
a +=1; 
alert("ceshisub"); 
}); 

The problem is that clicking the "click event" button in the page does not have any response. Open the js debugging window at var a=1; The breakpoint on this line does not enter.
The solution is:
I. add load event on the above js function:
The added code is as follows:
 
$(function(){ 
$("#ceshisub").bind("click",function(){ 
var a=1; 
a +=1; 
alert("ceshisub"); 
}); 
}); 

In this case, the binding event takes effect.
Js has three load functions, in addition to the above
 
$(function(){ 
alert(" The first 1 Kind of method. "); 
}); 

There are two other methods:
 
window.onload=function(){ 
alert(" The first 2 Kind of method. "); 
} 

$(document).ready(function(){ 
alert(" The first 3 Kind of method. "); 
}); 

Ii. If you do not use js loading function to initialize the binding event, there is another method:
The statement that will reference js
< Script language = "javascript" SRC = "/ js/test. Js" > < / script>
Load it at the end of the page.

Conclusion:
When jquery binds an event to an element A, it first looks for that element A in docment, and if it is not found, the binding fails.
The first solution above is to bind after the page is initialized and after the js is initialized
The second way is to make sure that the page elements are initialized before binding, at which point all elements are initialized and bound.

Related articles: