jquery click function in for loop only working in last loop [closed]

一笑奈何 提交于 2019-12-13 11:02:37

问题


I'm probably doing something obviously wrong, but I just can't see it. I'm trying to use a for loop to define multiple click events and am experiencing an unexpected result. Some of this is working (the hide and show at the beginning of the function, but both sections wind up targeting the second item in the loop. Could somebody take a look at this and tell me what I'm doing wrong? Thank you so much for your help!

here is the link: http://grana.us/test/expand2.html


回答1:


You are assigning same event to all summaries for every id. This is wrong...

First... to hide all details and show all toglers simply use:

$('.details').hide();
$('.toggler').show();

And then define click function to all sumaries:

$('.summary').click(function(){
   if($('.toggler',this).html() == ' -'){
      $('.toggler',this).html(' +');
      $('.details',$(this).parent()).hide();
   }else{
      $('.toggler',this).html(' -');
      $('.details',$(this).parent()).show();
   }
});

Put everything in...

$(function(){
   ...
});

and should be ok.



来源:https://stackoverflow.com/questions/19606438/jquery-click-function-in-for-loop-only-working-in-last-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!