我有一个 .tweet
类的项目列表,如果在 .tweet
的该实例中找到某个术语,我想要该元素的背景。
问题是,当 jQuery
找到关键字的一个实例时,所有 .tweet
元素都会更改其背景。如何将其与找到的术语隔离到元素?
if($('.tweet').find('goat')){
$('.tweet',this).css('background-color','#663399');
}
最佳答案
$('.tweet:contains("goat")') // find tweets with the word goat within
.css('background-color','#639'); // change only their background
我相信这就是你想要的。除非您正在寻找 <goat>
元素,.find
不是您需要的,而是 :contains
。因为您“链接”了该语句,所以它只会将 css 样式应用于匹配的元素。
并且,作为引用,上面的代码本质上是在做:
$('.tweet').each(function(){ // go through each .tweet
var $tweet = $(this); // a reference to the single tweet
if ($tweet.text().indexOf('goat') != -1){// check if the word "goat" is within
$tweet.css('background-color','#639'); // change the background color
}
});
关于jquery - 当元素 find() 时更改 DIV CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9526154/