Javascript jQuery - 检查标签的内容是否等于 sometext 然后做一些事情
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8604033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Check if the tag's content is equal to sometext then do something
提问by xperator
Let's say I have many of these in my content div
: <cite class="fn">blabla</cite>
假设我的内容中有很多这样的内容div
:<cite class="fn">blabla</cite>
How can I check every cite
tag's content(in this case: blabla
) with class fn
to see if it equals to "sometext" then change it's color to red ?
如何使用类检查每个cite
标签的内容(在这种情况下:)以查看它是否等于“sometext”,然后将其颜色更改为红色?blabla
fn
Very simple.
很简单。
回答by powerbuoy
$('cite.fn:contains(blabla)').css('color', 'red');
Edit: though that will match "blablablabla" as well.
编辑:虽然这也将匹配“blablablabla”。
$('cite.fn').each(function () {
if ($(this).text() == 'blabla') {
$(this).css('color', 'red');
}
});
That should be more accurate.
那应该更准确。
Edit: Actually, I think bazmegakapa's solution is more elegant:
编辑:实际上,我认为 bazmegakapa 的解决方案更优雅:
$('cite.fn').filter(function () {
return $(this).text() == 'blabla';
}).css('color', 'red');;
回答by kapa
You can make use of the amazing .filter()
method. It can take a function as its parameter, which will reduce the jQuery collection's elements to those that pass its test (for which the function returns true). After that you can easily run commands on the remaining elements:
你可以使用这个惊人的.filter()
方法。它可以将一个函数作为其参数,这会将 jQuery 集合的元素减少到通过其测试的元素(函数返回 true)。之后,您可以轻松地对其余元素运行命令:
var searchText = 'blabla';
$('cite.fn').filter(function () {
return $(this).text() === searchText;
}).css('color', 'red');
回答by isNaN1247
You could potentially do something like:
您可能会执行以下操作:
$('cite.fn').each(function() {
var el = $(this);
if (el.text() === 'sometext') {
el.css({ 'color' : 'red' });
}
});
This fires a function against each cite
that has the class fn
. That function checks if the current cite
's value is equal to 'sometext'.
这会针对每个cite
具有 class的函数触发一个函数fn
。该函数检查当前cite
的值是否等于 'sometext'。
If it is, then we change the CSS color
(text-color) property to red
.
如果是,那么我们将 CSS color
(文本颜色)属性更改为red
.
NoteI'm using jQuery in this example, as you've specifically tagged your question jQuery
. Ignore the downvote, this was applied before I edited a typo that I'd made (el.val()
rather than el.text()
)
注意我在这个例子中使用了 jQuery,因为你已经特别标记了你的问题jQuery
。忽略downvote,这是在我编辑我所做的错字之前应用的(el.val()
而不是el.text()
)
回答by Niet the Dark Absol
Without jQuery:
没有 jQuery:
var elms = document.querySelectorAll("cite.fn"), l = elms.length, i;
for( i=0; i<l; i++) {
if( (elms[i].innerText || elms[i].textContent) == "blabla") {
elms[i].style.color = "red";
}
}