Because I do not know how to describe this problem, so the title up so pit dad
The main process is this, today I write a similar to Baidu know that there are questions to answer the page, all the data is the first time the page is loaded through Ajax
The desired effect is that the questioner can choose to adopt this answer through the star symbol behind each answer, and the adopted answer Star icon will become All black.
That's what I wrote at first.
Copy Code code as follows:
$ ('. 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 each star class name
After running Click on the Stars no response
So I added an alert ("test") to the code snippet shown above.
When the page is loaded and the dialog box test is displayed, the event that the star icon is bound on can be performed correctly.
Search the Internet to find an answer, the result is that all of these answers are dynamically generated nodes, so it is possible that these nodes have not finished executing the event binding, so that there is no real event binding to the nodes generated these answers.
With alert, it is obvious that the alert statement executes after all data has been obtained, ensuring that the event bindings are executed after the data is loaded, so that the event is successfully bound to each answer.
http://img.blog.csdn.net/20140531202827265
Workaround, bind the event using on in jquery
Copy Code code as follows:
$ ("#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
All elements in this block class for Choose_right_answer If a click occurs, the event bubbles to Answer_wrap, executes the corresponding function, and the rest of the elements in this block occur when the Click event ignores
This will solve the problem of event binding in dynamic loading data