jquery 在 <td> 中查找文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4073427/
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 find text inside <td>
提问by coffeemonitor
I'm playing around with some selectors, and I'm hitting a wall with selecting Text inside a cell.
我正在玩一些选择器,并且在单元格内选择文本时遇到了麻烦。
Here's a simple attempt I'm making.
这是我正在做的一个简单尝试。
<table>
<tr>
<td>First Name</td>
<td>*required</td>
</tr>
</table>
I want to change the class for that cell to be "red" - if the string "*required" is found.
我想将该单元格的类更改为“红色” - 如果找到字符串“*required”。
Here's my attempt at the jquery:
这是我在 jquery 上的尝试:
$("td:contains('*required')").addClass("red");
It's causing all cells to apply that class, it seems. Any better ways to look for specific text?
它似乎导致所有单元格都应用该类。有没有更好的方法来查找特定文本?
回答by Nick Craver
What you have works, you can test it here, keep in mind that any parent<td>
alsocontains that text though, to do an exact match do this:
你有什么作品,你可以在这里测试,请记住,任何父级<td>
也包含该文本,要进行完全匹配,请执行以下操作:
$("td").filter(function() { return $.text([this]) == '*required'; })
.addClass("red");
回答by mway
You could always just use $.filter()
, where only elements that the callback returns true for are included in the selection. For example:
您始终可以只使用$.filter()
,其中只有回调为其返回 true 的元素包含在选择中。例如:
$('td').filter(function(i) {
$(this).html().indexOf('*required') >= 0;
});
Also: you'll want to be more specific with your selector - for efficiency, and also because of Nick's answer. Though if you're considering efficiency, you're better off not using a method that uses a callback in the first place. :)
另外:您需要更具体地使用您的选择器 - 为了效率,也因为尼克的回答。但是,如果您考虑效率,最好不要首先使用使用回调的方法。:)
As far as selectors go, consider using $('#tableID > tr > td')...
or something similar.
就选择器而言,请考虑使用$('#tableID > tr > td')...
或类似的东西。
回答by SnickersAreMyFave
You should not be using JavaScript to do this. What you should be using is a CSS class:
您不应该使用 JavaScript 来执行此操作。你应该使用的是一个 CSS 类:
<table>
<tr>
<td>First Name</td>
<td class="required">*required</td>
</tr>
</table>
<style type="text/css">
td.required {
color:red;
}
</style>