大家好,我正在尝试循环 2 个数组,一个数组处理按钮 Id,另一个数组处理文本。但是它似乎无法迭代文本数组。当我尝试 window.alert 值时,它返回未定义。
var buttonIdArray = ['#one', '#two']
var textArray = ['this is button one', 'this is button two']
function buttonDetails() {
for (var i = 0; i < buttonIdArray.length; i++) {
$(buttonIdArray[i]).click(function() {
window.alert(textArray[i])
})
}
}
<button id ='one'>one</button>
<button id ='two'>two</button>
最佳答案
由于 .click()
上下文中的 scope
不同,您需要先从 textArray
获取文本,如下所示:
var buttonIdArray = ['#one', '#two']
var textArray = ['this is button one', 'this is button two']
function buttonDetails() {
for (var i = 0; i < buttonIdArray.length; i++) {
const text = textArray[i]
$(buttonIdArray[i]).click(function() {
window.alert(text)
})
}
}
buttonDetails()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='one'>one</button>
<button id='two'>two</button>
关于javascript - 使用 for 循环访问 Jquery 内的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49617671/