gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:31:22 24 4
gpt4 key购买 nike

循环遍历表列时,列索引存储在变量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

最佳答案

您应该在循环外部定义变量,作为数组,

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

所以在外面它将显示控制台中的所有索引。

希望这对您有帮助。

关于javascript - 如何在其范围之外使用 THIS 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44636065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com