我正在尝试创建一个函数,当用户单击按钮时添加额外的文本字段。它的工作方式是实际上有四个文本字段和三个按钮。使用“display:none”隐藏四个文本字段中的三个,并隐藏三个按钮中的两个。 当您单击按钮 1 时,将显示文本字段 2 和按钮 2;当您单击按钮 2 时,将显示文本字段 3 和按钮 3,依此类推。这可以通过手动输入代码来管理,但当必须创建许多文本字段时,这会成为一种负担。到目前为止,我已经使用了这段代码:
<html>
<head>
<style type="text/css">
.hide {display:none;}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#add"+2 ).click(function(){
$("#add"+2).hide();
$("#text"+2).show();
$("#add"+3).show();
});
$("#add"+3 ).click(function(){
$("#add"+3).hide();
$("#text"+3).show();
$("#add"+4).show();
});
$("#add"+4 ).click(function(){
$("#add"+4).hide();
$("#text"+4).show();
});
});
</script>
</head>
<body><div id="border">
<form action="" method="post">
<table>
<tr>
<td>
<input type="text" id="text1" name="text1" />
</td>
<td>
<input type="button" id="add2" name="add" value="add another field" />
<input type="button" id="add3" class="hide" name="add" value="add another field" />
<input type="button" id="add4" class="hide" name="add" value="add another field" />
</td>
</tr>
<tr>
<td>
<input type="text" id="text2" class="hide" name="text2" /><br>
<input type="text" id="text3" class="hide" name="text3" /><br>
<input type="text" id="text4" class="hide" name="text4" />
<td>
</tr>
</table>
</form>
</div>
</body>
</html>
然后我更换了
$("#add"+2 ).click(function(){
$("#add"+2).hide();
$("#text"+2).show();
$("#add"+3).show();
});
$("#add"+3 ).click(function(){
$("#add"+3).hide();
$("#text"+3).show();
$("#add"+4).show();
});
用 for 循环尝试做同样的事情
var i = 2;
for (i=2; i<=3; i++)
{
$("#add"+i ).click(function(){
$("#add"+i).hide();
$("#text"+i).show();
$("#add"+(i+1)).show();
});
}
替换为 for 循环后,单击第一个按钮后仅显示第四个文本字段。这里有一些我不明白的逻辑吗?提前致谢。
最佳答案
您的内部函数有一个到外部 i
的闭包,因此当它访问 i
时,它访问的是变量本身,而不是它的值。
您可以使用自执行函数来打破这个问题,并将值传递给新的局部变量。
var i = 2;
for (i = 2; i <= 3; i++) {
(function(j) {
$("#add" + j).click(function() {
$("#add" + j).hide();
$("#text" + j).show();
$("#add" + (j + 1)).show();
});
})(i);
}
关于jquery - 使用 for 循环创建 jquery click 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6288571/