JS Pass a trigger to the value of a variable at the instant it is created

0

For example:

var items = jq(".li");
for(var i=0; i<items.length; i++){
    var item = jq(items[i]);
    item.click(function(i){
        console.log("i: ", i);
    });
}

The problem with this code is that when the click event is triggered, i debugs undefined. I imagine that this happens because it is at that moment when it will look for the value of i which no longer exists because the loop has ended.

How can I solve this? I can not pass a parameter to an anonymous function.

Thanks in advance.

    
asked by Adrià Fàbrega 23.05.2018 в 16:43
source

1 answer

0

This possibility occurs to me, basically add an attribute to each element that will save the value of i :

var items = jq(".li");
    for(var i=0; i<items.length; i++){
        var item = jq(items[i]);
        item.attr("dato",i);
        item.on("click",() => {
            console.log("i: ", jq(this).attr("dato"));
        });
    }

I hope it works for you:)

Another possible option that has occurred to me:

var items = jq(".li");
    for(var i=0; i<items.length; i++){
        var item = jq(items[i]);
        item.attr("dato",i);
        item.on("click",(i) => {
            paraCallback(i);
        });
    }

function paraCallback(i){
    console.log("i: ", i);
}
    
answered by 23.05.2018 / 16:51
source