我只是想点击一下隐藏答案的问题清单.我的代码隐藏了所有div,但是当我单击锚点时,只切换最后一个框.在这种情况下,每个锚都会切换第5个框,而不是自己的框.
for(var i=1; i<6; i++){
var x = i+"";
$("#box"+ x).hide();
$("#feature"+x).click(function(){
$("#box"+x).toggle(400);
});
}
Run Code Online (Sandbox Code Playgroud)
我的基本HTML看起来像这样,但有5对:
<p><a id="feature1" href="#">1. Absent Message</a></p>
<div id="box1">Stuff here 1</div>
<p><a id="feature2" href="#">2. Alarm Setting</a></p>
<div id="box2">Stuff here 2</div>
Run Code Online (Sandbox Code Playgroud)
如果我在不使用for循环和字符串连接的情况下写出函数,函数就会按照我的要求执行.有人能指出我正确的方向吗?我在字符串操作方面做错了吗?
你的问题是在循环的所有副本x之间共享,所以最后它始终是,并且总是在它在点击时附加的时候.更简单的方法是类,如下所示:5$("#box"+x)$("#box5")
<p><a class="feature" href="#">1. Absent Message</a></p>
<div class="box">Stuff here 1</div>
Run Code Online (Sandbox Code Playgroud)
然后找到它,就像这样:
$(".box").hide();
$(".feature").click(function() {
$(this).parent().next(".box").toggle(400);
});
Run Code Online (Sandbox Code Playgroud)
如果这不是一个选项,您需要为循环提供必要的范围,如下所示:
for(var i=1; i<6; i++){
(function(x) {
$("#box"+ x).hide();
$("#feature"+x).click(function(){
$("#box"+x).toggle(400);
});
})(i);
}
Run Code Online (Sandbox Code Playgroud)
通过这样做,我们将传递i给匿名函数,该函数调用自己的副本x,而不是作为for循环所在函数的共享变量(这是当前正在发生的事情).