Home > Web Front-end > JS Tutorial > Detailed explanation of the problem of binding events in JQuery loop

Detailed explanation of the problem of binding events in JQuery loop

韦小宝
Release: 2017-11-29 11:22:48
Original
1714 people have browsed it

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="" />
Copy after login

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++){
  $(&#39;#username_&#39;+i).onclick(function(){
   alert(i);
  });
 }
});
Copy after login

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);
 }
});
Copy after login

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!

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