There is a page that requires N DOMs. If we need to manually bind jQueryevents to the DOM, the workload will be huge, and the amount of code will also be When it increases, it looks messy. At this time, we can use jQueryLoop to bind events to reduce the workload and the amount of jQuery code. Without further ado, let’s take a look!
There is a page that requires N DOMs. The element ID in each DOM must end with a number. For example:
<input type="text" name="username" id="username_1" value="" /> <input type="text" name="username" id="username_2" value="" /> <input type="text" name="username" id="username_3" value="" />
Now there is a loop, which is required when the page is loaded. Add an onclick event to each element. It is easy to think of writing
$(function(){ for(var i=1; i<=3; i++){ $('#username_'+i).onclick(function(){ alert(i); }); } });
which is wrong. . .
Then change it to the following:
$(function(){ for (var i=1; i<=3; i++){ $("#username_"+i).bind("click", {index: i}, clickHandler); } function clickHandler(event) { var i= event.data.index; alert(i); } });
The above is a detailed explanation of the problem of JQuery binding events in a loop. For more information, please go to this siteSearch.
Related recommendations:
Code based on jquery loop map function_jquery
JQuery loop scrolling picture code_jquery
jQuery loop scrolling news list sample code_jquery
The above is the detailed content of Detailed explanation of the problem of binding events in JQuery loop. For more information, please follow other related articles on the PHP Chinese website!