0

有没有办法把它变成一个 for 循环?我必须运行这段代码 114 次,并且正在寻找一种方法来简化它。类名上的数字将是变量。下一个将是 .select3 等...

$('.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");
        };
    });
4

2 回答 2

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);
}
于 2012-09-18T01:50:49.617 回答
-1

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

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

.each()如果您想获得所有物品,请使用:

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

但在您的情况下,您可以像这样简单地应用“点击”事件:

$('.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
});
于 2012-09-18T02:17:14.093 回答