<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js
"></script>
<script type="text/javascript">
$(function(){
for(i=0;i<5;i++){
var ids=[1,2,3,4,5];
$("#btn"+ids[i]).click(function(){
alert("btn"+ids[i]);
});
}
});
</script>
</head>
<body>
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
<button id="btn3">按钮3</button>
<button id="btn4">按钮4</button>
<button id="btn5">按钮5</button>
</body>
</html>
单击该按钮应警告数组中的值,但它会警告btnundefine
。
如何在lambda函数中访问外部数组中的值?
答案 0 :(得分:2)
使用let
定义i。否则,它将尝试访问ids [5]并打印undefined,因为ids数组只有5个元素。
$(function(){
var ids=[1,2,3,4,5];
for(let i=0;i<5;i++){
$("#btn"+ids[i]).click(function(){
alert("btn"+ids[i]);
});
}
});
<script typetype=="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
<button id="btn3">按钮3</button>
<button id="btn4">按钮4</button>
<button id="btn5">按钮5</button>
答案 1 :(得分:-1)
这也是可行的:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js
"></script>
<script type="text/javascript">
$(function(){
var ids=[1,2,3,4,5];
for(i=0;i<5;i++){
console.log("#btn"+ids[i]);
$("#btn"+ids[i]).click(function(){
alert(this.id);
});
}
});
</script>
</head>
<body>
<button id="btn1">按钮1</button>
<button id="btn2">按钮2</button>
<button id="btn3">按钮3</button>
<button id="btn4">按钮4</button>
<button id="btn5">按钮5</button>
</body>
</html>