【问题标题】:if or statement within jquery $.each valuesjquery $.each 值中的 if 或语句
【发布时间】:2013-05-04 13:19:11
【问题描述】:

是否有更有效的方法来执行以下 javascript 代码?我很想把它剪下来,但想不出办法。谢谢!

      var sizes = []; //This is a dynamic array from button clicks in an above menu that will include any of ['S','M','L','XL']
      sizes = ['S','M'] // We'll use this as an example saying that the S and M buttons are active.
      $('div').each(function() {
        var t = $(this);
        var mysizes = t.attr('class').split(/\s+/);
        var length = sizes.length;
        if(length == 0) {
            t.show();
        }
        if(length == 1) {
            if(t.hasClass(sizes[0])) {
                t.show();
            } else {
                t.hide();
            }
        }
        if(length == 2) {
            if(t.hasClass(sizes[0]) || t.hasClass(sizes[1])) {
                t.show();
            } else {
                t.hide();
            }
        }
        if(length == 3) {
            if(t.hasClass(sizes[0]) || t.hasClass(sizes[1]) || t.hasClass(sizes[2])) {
                t.show();
            } else {
                t.hide();
            }
        }
        if(length == 4) {
            if(t.hasClass(sizes[0]) || t.hasClass(sizes[1]) || t.hasClass(sizes[2]) || t.hasClass(sizes[3])) {
                t.show();
            } else {
                t.hide();
            }
        }
    });

任何帮助将不胜感激。

【问题讨论】:

    标签: jquery if-statement each performance


    【解决方案1】:

    类似的东西

    $(document).ready(function(){
       var sizes = []; 
       sizes = ['s','m'];
       $("div").hide();
       $.each(sizes, function(index, item) {
           $("."+item).show();
       });
    });    
    

    jsfiddle

    【讨论】:

    • 我有一些非常接近这个概念的东西,但无法让它发挥作用。这是完美的,谢谢!
    【解决方案2】:

    做这样的事情

    t.hide();
    if(length > 0){
        for (i = 0; i < length; ++i) {
            for (j = 0; j <= i; ++j) {
                if(t.hasClass(sizes[j])) {
                        t.show();
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-05
      • 1970-01-01
      • 2018-04-02
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多