Solution to the problem of nesting a click event in for loop of JavaScript

  • 2021-07-26 06:05:15
  • OfStack

Look at the following code first:


for(var i=0; i<10; i++) {
 $('#ul').bind('click', function() {
  alert(i)
 })
}

For this code, when you click on an element whose Id is "ul", 10 10s pop up. Why do 10 10s pop up?

First of all, the click event in this code is not a binding event, but a binding event of jQuery, so there is a difference between binding events and ordinary events. In ordinary events, if multiple click events are added to a certain element, the last one will cover all the previous click events, and only the last one can be executed; However, in the binding event, it is not the same. On the same element, even if more clicks are bound, they will all be executed. That is, onclick in ordinary events only supports a single event and will be overwritten by other onclick events, while click events in event bindings can add multiple events without worrying about being overwritten. Then, it is conceivable that when you click on the element where Id is "ul", 10 pop-up windows will pop up.

If you still don't understand it, it will be easy to understand it after deformation of the code.

In fact, the above code can be transformed into the following form:


// i=0 Hour 
$('#ul').bind('click', function() {
  alert(i)
 })
// i=1 Hour 
$('#ul').bind('click', function() {
  alert(i)
 })
 
......
 
// i=10 Hour 
$('#ul').bind('click', function() {
  alert(i)
 })

Extension: The following code is a comparison of the original code above, and one step further explains the difference between ordinary events and event binding


for(var i=0; i<10; i++) {
 document.getElementById('ul').onclick = function() {
  alert(i)
 }
}

Running result: 1 10 pops up

Obviously, when the click event is triggered, 10 pop-up windows will pop up. Then, there may be questions again? Why are there 10 10s? Shouldn't it be 0, 1, 2, 3... 10? To solve this doubt, the original code can be deformed again:


var i=0
 
$('#ul').bind('click', function() {
  alert(i)
 })
i=1
$('#ul').bind('click', function() {
  alert(i)
 })
 
......
 
i = 9
$('#ul').bind('click', function() {
  alert(i)
 })

After the original code is deformed like this, it is obvious that the final value of i is 9, but according to the principle of for loop, i + + will be executed after i is 9, and then i will be judged < 10. At this time, the condition is no longer met, so the loop is terminated, and the final i value is 10. Then it is natural to understand why the final result is 10 pop-up windows with a result of 10.

Summary: This code seems simple, but it covers many knowledge points such as event binding, common events, for loop and so on.


Related articles: