我尝试使用 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');
});
关于jquery - 使用 jQuery 检查 id 和 class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042025/