2012-09-18 63 views
0

功能有没有办法变成一个for循环?我必须运行此代码114次,并正在寻找一种方法来简化此操作。类名称上的数字是变量。下一个会是.select3等等JQuery的for循环 - 与变量

$('.select2').click(function() { 
     if ($('.saved_list .thumb2').length == 0 && $('.saved > li').length < totalPic) 
      { 
       $(this).parent().clone().appendTo('.saved_list ul'); 
       $('.saved .select2').replaceWith('<div class="remove2">Remove</div>'); 
       $('.saved a').contents().unwrap(); 
      } else { 
       alert ('You can only choose 3 paintings'); 
      } 
      if ($('.saved_list li').has('.thumb2')) { 
       $(".select2 .img-swap").attr("src", "images/check_on.gif"); 
      } else { 
       $(".select2 .img-swap").attr("src", "images/check_off.gif"); 
     }; 
    }); 
+0

没有必要为一个循环..只是使它更加灵活..显示你的HTML –

+0

那岂不是更容易给他们的所有一个共同的类名,那么你可以只使用一个单一的选择对所有的人? – Barmar

回答

2

试试这个:

var run_select = function(index){ 
    var selector = '.select'+index; 
    $(selector).click(function() { 
     if ($('.saved_list .thumb2').length == 0 && $('.saved > li').length < totalPic) 
     { 
      $(this).parent().clone().appendTo('.saved_list ul'); 
      $('.saved '+selector).replaceWith('<div class="remove2">Remove</div>'); 
      $('.saved a').contents().unwrap(); 
     } else { 
      alert ('You can only choose 3 paintings'); 
     } 
     if ($('.saved_list li').has('.thumb2')) { 
      $(selector+" .img-swap").attr("src", "images/check_on.gif"); 
     } else { 
      $(selector+" .img-swap").attr("src", "images/check_off.gif"); 
     }; 
    }); 
}; 
var i, l = 114; 
for(i=1;i<=114;i++){ 
    run_select(i); 
} 
-1

首先,如果你可以简化HTML。使用id作为唯一标识符,并为css类使用相同的名称。就像这样:

<div id='select2' class='select'></div> 

然后使用.each()如果你想获得所有项目:

$('.select').each(function() { 
    // use $(this) here to refer to the current item 
}); 

但在你的情况,你可以简单地套用这样的“click”事件:

$('.select').click(function(e) { 
     // use $(this) or $(e.target) here to refer to the current item 
     // if you need to get the id number you could get it from the id 
     // (supposing has id='select2') 

     var id = $(this).attr('id').substring(6); // it returns 2 
}); 
+0

这将是有趣的知道为什么这个答案已经downvoted ... – taseenb