如何在 for 循环中维护迭代变量的原始值,该循环设置事件调用,其中迭代值是函数的一部分

How do you maintain the original value of an iterated variable in a for loop that sets event calls where the iterated value is part of the function?

本文关键字:循环 迭代 事件 调用 一部分 函数 设置 原始 for 维护 变量      更新时间:2023-09-26

请帮我解决这个问题:

这组代码中有不确定的迭代次数:

var c = 1;
for(c=1; c<x; c++){
    $('#'+l_id+'_'+c).on("keypress", function(f){
        com_guide_add_li((c+1), $(this).parent().parent().attr('id'), f);
    })
}

问题是,当调用事件时,(c+1) 是上次迭代 + 1 的值,而不是此代码运行时迭代期间某个位置的值。

如何确保 (c+1) 的原始值保留在函数调用中,即设置事件调用的迭代运行时的值?

谢谢

*对不起,标题很长

我认为这应该有效,早期绑定应该会处理它。

var c = 1;
for(c=1; c<x; c++){¡   
     var tmp_var = c;        
     $('#'+l_id+'_'+c).on("keypress", function(f){                  
        com_gude_add_li((tmp_var+1), $(this).parent().parent().attr('id'), f);
    })
}

让我知道这是否有帮助。

选项 2

由于您使用的是jquery,因此可以使用data方法(更多内容可在此处阅读):

var c = 1;
    for(c=1; c<x; c++){¡   
        $('#'+l_id+'_'+c).data("c", c);
        $('#'+l_id+'_'+c).on("keypress", function(f){            
            com_gude_add_li(($(this).data("c") + 1), $(this).parent().parent().attr('id'), f);
        })
    }