简体   繁体   中英

Alert only when i click on the element not sequentially

How to modify this code to alert with the current value of 'i' when i only click on the 'elem' not sequentially.

Example:

first click alert 1 , second click alert 2 , and so on ..

for (var i = 1; i <= 3; i++) {
  (function(i){
    $elem.click(function() { alert(i); });
  })(i);
}

When i run this code and click on the 'elem' then 3 messages will alert sequentially with the values of 'i' ( 1 , 2 ,3 ), I was expecting that it will only alert when i click on the 'elem' not sequentially .

This should do it:

var i = 0;
$('elem').click(function() { i++; alert(i) });

First click returns 1, second: 2 and third: 3. If you want it to start over when it hits 3, then add this to the function:

i = i == 3 ? 0 : i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM