How to call a function by a value that may change?

I have some functions that start when an element is clicked. Elements are stored in an array. But the value that calls the function changes. Here is the code for the function:

// first I store the element of a list in an array var promo = new Array(), indexOfTheElement = 3; $('#list li').each(function(){ promo.push($(this)); }); $(myArray[indexOfTheElement]).click(function(){ indexOfTheElement--; // Do something return false; }); 

Edit: The list item is stored in an array, and the function runs when the list item is clicked. For example, if you click on the third element, the function will be launched, and then it will work when you click on the second.

+4
source share
3 answers

This may be a scope problem, but I believe you want to use bind () and unbind () for every function call. For instance:

 var foo = function(){ myArray[index].unbind("click"); index--; //do something myArray[index].bind("click", foo); return false; } 
+2
source

Inside the event handler, cancel the current event handler and install a new one, just declare the function (do not use an anonymous function) when you set click ().

 $(myArray[indexOfTheElement]).click(doSomething); function doSomething() { $(myArray[indexOfTheElement]).off("click", doSomething); $(myArray[--indexOfTheElement]).click(doSomething); return false; } 
0
source

try using live() and the code inside $(document).ready()

 $(document).ready(function(){ var promo = new Array(), indexOfTheElement = 3; $('#list li').each(function(){ promo.push($(this)); }); $(myArray[indexOfTheElement]).live('click',function(){ indexOfTheElement--; // Do something return false; }); }); 
0
source

Source: https://habr.com/ru/post/1401117/