JQuery binding events do not execute but alert does

  • 2020-03-30 03:07:40
  • OfStack

Because I don't know how to describe this problem, so the title of the pit dad

The main process is like this. Today, I wrote a page with questions and answers like baidu knows. All the data was obtained through ajax when the page was loaded for the first time
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201406/201406030951195.gif? 2014539524 ">  
The hope is that the questioner can choose to adopt the answer by the star symbol at the end of each answer. The star icon of the adopted answer will become all black.

I started with this
 
$('.choose_right_answer').bind('click',function(){ 
if(currentUser==questioner) { 
if ($(this).attr("src") == "img/star_fav_empty.png") 
$(this).attr("src", "img/star_fav.png"); 
else 
$(this).attr("src", "img/star_fav_empty.png"); 
} 
}); 

.choose_right_answer is the class name of each star

After running, clicking on the star did not respond

So I put an alert("test") before the code snippet shown above

After the dialog box test pops up after loading the page, the events bound on the star icon can execute normally.

A search of the web for answers yields the result that since all of the answer nodes are dynamically generated, the event binding may be performed before the nodes are finished executing, so that the event is not actually bound to the node where the answer is generated.

With the addition of alert, it is clear that the alert statement is executed after all the data is available, ensuring that the event binding is executed after the data is loaded, so that the event is successfully bound to each response.
http://img.blog.csdn.net/20140531202827265
The solution is to use on in jQuery to bind events
 
$("#answer_wrap").on('click','.choose_right_answer',function(){ 
if(currentUser==questioner) { 
if ($(this).attr("src") == "img/star_fav_empty.png") 
$(this).attr("src", "img/star_fav.png"); 
else 
$(this).attr("src", "img/star_fav_empty.png"); 
} 
}); 

Answer_wrap is the id of the block where all the answers are located

All elements in the block with class choose_right_answer will bubble to the answer_wrap if a click occurs, and the rest of the elements in the block will be ignored if a click occurs

This solves the problem of event binding in dynamically loaded data

Related articles: