Home  >  Article  >  Web Front-end  >  Problems related to the process of binding events to elements in batches in JS are solved using closures_jquery

Problems related to the process of binding events to elements in batches in JS are solved using closures_jquery

WBOY
WBOYOriginal
2016-05-16 17:36:58855browse

In JS, when you write a for loop, the internal loop variable I will actually be saved in the function or class it runs, so you will find that when you batch-bind events to elements, i = the last one appears. The value of the loop variable is very confusing. There are two solutions.
The idea is: save this loop variable, do not let its scope be in the entire function, but within the loop body

1. Use closures (if you don’t understand closures, please open Baidu: www.baidu.com)
2. Use the with keyword, the with syntax is with(obj) { //so that you can directly use it here Access the properties of obj without adding obj.