jquery - 当元素 find() 时更改 DIV CSS

标签 jquery

我有一个 .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/

相关文章:

javascript - 使 slider 气泡跟上左 handle

javascript - 透明HTML

jquery - 为什么 jquery Mega Menu 在 IE7 和 9 中显示在我的图像后面?

jquery - 无论上传的图像大小如何,如何将动态创建的 Bootstrap 轮播图像的大小设置为桌面大小

php代码没有按预期获取文件

jquery - 如何在脚本中的 fadeOut 函数后刷新页面?

javascript - 如何使用Jquery查找最近的父元素属性值

javascript - 如何在工具提示中包含类别数据

javascript - 无效的 prop : type check failed for prop "items". 预期数组,得到字符串

javascript - 尽管经过 Chrome 开发工具控制台验证,jQuery slice() 仍无法正常工作