2011-06-09 42 views
4

我试图创建一个函数,当用户单击一个按钮时添加一个额外的文本字段。它的工作方式是实际上有四个文本字段和三个按钮。四个文本字段中的三个用“display:none”隐藏,三个按钮中的两个隐藏。 当您单击按钮1时,显示文本框2和按钮2,并且当您单击按钮2时,显示文本框3和按钮3等等。这是可以通过手动输入代码来管理的,但是当必须创建许多文本字段时,这成为一种负担。到目前为止,我用这个代码:用for循环创建jquery点击函数

<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(); 
      }); 
} 

与置换了之后循环中,单击第一个按钮后仅显示第四个文本字段。有没有我在这里不理解的逻辑?提前致谢。

回答

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); 
} 
+0

如何语法工作当您添加 “(我)” 接近尾声? – user701510 2011-06-09 06:25:36

+0

@user函数是一流的。所以我创建了一个匿名函数,然后用'()'执行它。结尾'()'中的参数被传递给匿名函数。 – alex 2011-06-09 06:29:01

+0

+1很好解释...非常有帮助。 – Codemwnci 2012-05-30 14:08:31

0

您可以测试此:

$(':button').click(function(e) { 
    var index = $(e.target).index(); 
    $('.add:eq(' + index + ')').hide(); 
    $('input:text:eq(' + (index + 1) + ')').show(); 
    $('.add:eq(' + (index + 1) + ')').show(); 
});