使用 jQuery 检查 id 和 class

Check id and class using jQuery

我已经尝试用 jQuery 检查我的 id,我想知道为什么它不起作用。我做错了什么?

<td class="food" id="butter">
    butter
</td>
<td class="food" id="milk">
    milk
</td>
$(function(){
    if ($('.food').attr('id') == "butter"){
        $('.food').css({ color: 'red' });
    } else { 
        $('.food').css({ color: 'blue' });
    }
});

全部显示为红色。有任何想法吗?非常感谢。

首先有多个 .food 元素,所以你需要使用 each() 循环,然后在该循​​环中你需要使用 this 仅引用当前元素。试试这个:

$('.food').each(function() {
    if (this.id == "butter"){
        $(this).css({ color: 'red' });
    } else { 
        $(this).css({ color: 'blue' });
    }
});

然后您可以使用三元进一步缩短它:

$('.food').each(function() {
    $(this).css('color', this.id == 'butter' ? 'red' : 'blue');
});

Working example

或没有.each():

$(".food").css({color: 'blue'}).filter("#butter").css({color: 'red'});