css 应用于数组中的所有元素

css being applied to all elements in array

当我运行这个函数时,CSS被应用到所有按钮。我该如何修改,以便 CSS 仅针对 buttonAttr 属性等于禁用的按钮进行修改?

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

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

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

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

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

我会建议这个小修改;

$('.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' />

不用写长代码就用这个

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

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

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