如何在 $(document).ready(function(){}) 中使用 for 循环

How can I use a for-loop within a $(document).ready(function(){})?

本文关键字:循环 for ready document function      更新时间:2023-09-26

我一直在尝试修改我在这里找到的代码:http://www.w3schools.com/jquery/jquery_hide_show.asp将多个隐藏按钮与多个段落链接。段落/按钮的数量是可变的——所以我需要它与 for 循环或 while 循环一起使用。

到目前为止,我已经让它工作了:

<script>
  $(document).ready(function(){
    $('.x'+1).click(function(){ $('.file'+1).toggle(1000);});
    $('.x'+2).click(function(){ $('.file'+2).toggle(1000);});
    $('.x'+3).click(function(){ $('.file'+3).toggle(1000);});
  });

</script>
</head>
<body>

<li class="file1">This is a paragraph with little content.</li>
<button class="x1">hide</button>
<p>
<li class="file2">This is another small paragraph.</li>
<button class="x2">hide</button>
<p>
<li class="file3">This is a paragraph.</li>
<button class="x3">hide</button>
</body>
</html>

但是当我尝试用for循环替换$(document).ready(function(){})的内部时,它就停止工作了。那么,为什么下面的代码不做任何事情呢?

var m,k=3;
  $(document).ready(function(){
  for (m = 1; m <=k; m++) {
    $('.x'+m).click(function(){ $('.file'+m).toggle(1000);});
    }
  });

你的html有问题,所以假设按钮和目标元素不是兄弟姐妹,你可以

<li class="file1">This is a paragraph with little content.</li>
<button class="x" data-target=".file1">hide</button>
<li class="file2">This is another small paragraph.</li>
<button class="x" data-target=".file2">hide</button>
<li class="file3">This is a paragraph.</li>
<button class="x" data-target=".file3">hide</button>

然后

$(document).ready(function () {
    $('.x').click(function () {
        $($(this).data('target')).toggle(1000);
    });
});

演示:小提琴

更新到此代码。演示

 $(document).ready(function(){
    $('button[class^="x"').click(function(){ $(this).prev('li').toggle(1000);});
 }); 

此外,您的HTML无效,因此请编写正确的HTML代码,以便我可以更详细地解释

使用循环尝试.each

$('button[class^=x]').click(function(){ 
    $(this).prev("li").toggle(1000);
});

演示

这将按照您计划的方式进行,即使用 for 循环

$(document).ready(function() {
function addClickHandler(i) {
    $('.x'+i).click(function(){ $('.file'+i).toggle(1000);});
}
var j;
for(j = 1; j <=3; j++) {
    addClickHandler(j);
}
});

但是我会做这样的事情

$(document).ready(function() {
  $(".file button").click(function() {
    $(this).prev().toggle(1000);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="file">
  <p>This is file 1</p>
  <button>Click me</button>
</div>
<div class="file">
  <p>This is file 2</p>
  <button>Click me</button>
</div>
<div class="file">
  <p>This is file 2</p>
  <button>Click me</button>
</div>

您将使用更少的类名,即file1,file2和x1,x2等。

这里已经有很多很好的答案了。我想特别补充一些关于JavaScript的关键内容。

问题不在于function中的for循环,而在于for循环中的function定义。

function的编译时间与其执行时间不同。在您的示例中,编译时间是在 for 循环期间,执行时间是在单击时。您如何期望您的变量m在编译时与执行时相同?如果不一样,你的代码如何工作?

一旦你的代码离开循环,任何事情都可能发生在m,并且在点击时,m 不像你预期的那样有效。

这只是一个例子,这里有更多关于为什么在循环中定义function可能令人费解的信息:http://jslinterrors.com/dont-make-functions-within-a-loop