【发布时间】:2011-06-09 05:45:59
【问题描述】:
我正在尝试创建一个在用户单击按钮时添加附加文本字段的函数。它的工作方式是实际上有四个文本字段和三个按钮。四个文本字段中的三个使用“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 循环后,单击第一个按钮后仅显示第四个文本字段。这里有一些我不理解的逻辑吗?提前致谢。
【问题讨论】:
标签: jquery forms function loops button