使用for循环创建jquery单击函数

use*_*510 4 forms jquery loops function button

我正在尝试创建一个函数,在用户单击按钮时添加其他文本字段.它的工作方式是实际上有四个文本字段和三个按钮.使用"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>
Run Code Online (Sandbox Code Playgroud)

然后我换了

    $("#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();
      });
Run Code Online (Sandbox Code Playgroud)

用for循环来尝试做同样的事情

var i = 2;
for (i=2; i<=3; i++)
{
 $("#add"+i ).click(function(){
        $("#add"+i).hide();
        $("#text"+i).show();
        $("#add"+(i+1)).show();
          });
}
Run Code Online (Sandbox Code Playgroud)

用for循环替换后,单击第一个按钮后只显示第四个文本字段.有什么逻辑我不明白吗?提前致谢.

ale*_*lex 13

你的内部函数有一个闭包到外部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);
}
Run Code Online (Sandbox Code Playgroud)