仅当css使用jQuery中的某些文本内容时,如何将css应用于该元素? [英] How do I apply css to an element only if it has certain text content in it using jQuery?

查看:128
本文介绍了仅当css使用jQuery中的某些文本内容时,如何将css应用于该元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://jsfiddle.net/aWp2g/2/

css

.highlight {
    color: yellow;
}

html

<div>fox</div>
<div>brown</div>

jQuery

if ($('div').text() == 'fox') {
    this.addClass('highlight');
}

我的上述代码无法正常工作,我希望它能为包含某个文本的元素,以便它应用突出显示的css。

My above code is not working, I want it to add a class to the element containing a certain text so that it applies a highlighting css.

推荐答案

在你的代码中引用窗口对象。
.text()方法返回所有选定元素的文本内容,返回值为: foxbrown 这不等于 fox

this in your code refers to window object. .text() method returns text content of all the selected elements, the returned value is: foxbrown which is not equal to fox.

你可以使用:contains 选择器用于选择包含特定文本的元素:

You can use :contains selector for selecting elements that contain a specific text:

$('div:contains(fox)').addClass('highlight');

完全匹配:

$('div').filter(function() {
   return (this.textContent || this.innerText) === 'fox';
}).addClass('highlight');

这篇关于仅当css使用jQuery中的某些文本内容时,如何将css应用于该元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆