【问题标题】:JQuery for loop - function with variablesJQuery for loop - 带变量的函数
【发布时间】:2012-09-18 01:37:36
【问题描述】:

有没有办法把它变成一个 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");
        };
    });

【问题讨论】:

  • 不需要循环.. 让它更灵活.. 显示你的 html
  • 给它们一个共同的类名不是更容易吗,然后你可以只为它们使用一个选择器?

标签: javascript jquery variables loops


【解决方案1】:

试试这个:

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);
}

【讨论】:

    【解决方案2】:

    首先,尽可能简化 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
    });
    

    【讨论】:

      猜你喜欢
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 2021-09-29
      • 2015-01-04
      • 1970-01-01
      相关资源
      最近更新 更多