【问题标题】:creating jquery click functions with for loop使用 for 循环创建 jquery click 函数
【发布时间】: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


    【解决方案1】:

    您的内部函数对外部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);
    }
    

    【讨论】:

    • @user 函数是一流的。所以我创建了一个匿名函数,然后用() 执行它。结尾 () 中的参数被传递给匿名函数。
    【解决方案2】:

    你可以测试一下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2022-01-13
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 2014-10-20
      相关资源
      最近更新 更多