如何在其范围之外使用THIS变量?

时间:2017-06-19 16:56:02

标签: javascript jquery

循环遍历表列时,列索引存储在变量columnIndex中。 在循环中,变量是定义的,但不在其外部。 如何在函数外部存储变量以使用它?

    $('#excel_table td:nth-child(1)').each(function(){
        var columnIndex = $(this).index();
        //SOME CODE...
        console.log(columnIndex);//RESULT = 1
    }); 
    console.log(columnIndex);//RESULT = Not defined

3 个答案:

答案 0 :(得分:4)

您应该在循环外定义变量,如数组

var columnIndex = [];

$('#excel_table td:nth-child('+ (1) + ')').each(function(i){
        columnIndex[i] = $(this).index();
        //SOME CODE...
        console.log(columnIndex);//RESULT = 1
    }); 
    console.log(columnIndex);//RESULT = Not defined

所以外面会显示控制台中的所有索引。

希望这会对你有所帮助。

答案 1 :(得分:3)

max()

答案 2 :(得分:1)

在范围之外定义:

var columnIndex = "";
$('#excel_table td:nth-child('+ (1) + ')').each(function(){
    columnIndex = $(this).index();
    //SOME CODE...
    console.log(columnIndex);//RESULT = 1
}); 
console.log(columnIndex);//RESULT = Not defined

这将允许访问每个。

相关问题