【问题标题】:css being applied to all elements in array [closed]CSS被应用于数组中的所有元素[关闭]
【发布时间】:2018-05-20 18:14:33
【问题描述】:

当我运行此函数时,CSS 将应用于所有按钮。如何修改,以便仅针对 buttonAttr 属性等于 disabled 的按钮修改 CSS?

$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');     
    } else {
        $this.css('background','#EEDED1');
    }   
});

【问题讨论】:

    标签: jquery foreach each


    【解决方案1】:

    您不应使用attr 函数检查布尔属性。使用prop 代替返回实际值。

    $('.product_tile .addtocartbutton').each(function(){
        $(this).prop('disabled') ? $(this).css('background','#ccc') : $(this).css('background','#EEDED1');
    });
    

    【讨论】:

      【解决方案2】:

      您需要两个或三个等号来进行比较。

       if($this.buttonAttr == 'disabled')
      

      【讨论】:

      • 谢谢,我注意到我还必须更改我的 if 条件。
      【解决方案3】:

      不用写长代码就用这个

       $(':button[disabled="disabled"]').css('background','#ccc');
      

      $('.product_tile .addtocartbutton :button[disabled="disabled"]')).css('background','#ccc');
      

      取决于您的情况。
      使用 :button 适用于按钮和输入 type="button"

      【讨论】:

        【解决方案4】:

        我会建议这个小修改;

        $('.product_tile .addtocartbutton').each(function(){
            var $this = $(this);
        
            if($this.is(":disabled")){
                $this.css('background','#ccc');     
            } else {
                $this.css('background','#EEDED1');
            }   
        });
        

        这利用了 jquery :disabled 选择器,link 到文档。


        编辑: 另一种选择是纯 CSS 解决方案,利用 attribute selector

        input[type='button'] {
          background: #eeded1;
        }
        
        input[type='button'][disabled] {
          background: #ccc;
        }
        <input type='button' value='Disabled' disabled='disabled' /><br /><br />
        <input type='button' value='Active' />

        【讨论】:

        • @Taplar,我进行了编辑以包含一个纯 css 解决方案。我认为这将是最有效的解决方案。
        猜你喜欢
        • 2015-06-26
        • 2021-10-13
        • 2014-07-29
        • 2017-08-22
        • 2017-03-25
        • 1970-01-01
        • 1970-01-01
        • 2023-01-24
        • 2015-01-31
        相关资源
        最近更新 更多