Javascript JQuery .addclass 到表 <tr> 元素,其中找到文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8056509/
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 .addclass to table <tr> element where text is found
提问by Danny Englander
I am theming some report tables and do not have access to the templates.
我正在对一些报告表进行主题化,但无权访问模板。
I have this code so far which ends up adding "my-class" to every TR element in the report table. However, I only want to add the class to the table row TR where the text was found. I am thinking I need a little more code to do this. Here are a few things I have tried so far:
到目前为止,我有这段代码,最终将“my-class”添加到报告表中的每个 TR 元素。但是,我只想将类添加到找到文本的表行 TR。我想我需要更多的代码来做到这一点。以下是我迄今为止尝试过的一些方法:
if ($('#report-area table tr:contains("Name")', this).length > 0) {
$("#reportArea table tr", this).addClass("my-class");
}
I have also tried:
我也试过:
if ($('#report-area table tr:contains("Name")', this).length > 0) {
$(this).addClass("my-class");
}
... but that did not work either.
......但这也不起作用。
回答by Blazemonger
Just use the selector with no fluff:
只需使用没有绒毛的选择器:
$('#report-area tr:contains("Name")').addClass('my-class');
回答by Seth
var $rows = $('#report-area table tr');
$rows.each(function(i, item) {
$this = $(item);
if ( $this.text() == 'Name' ) {
$this.addClass('yourClass');
}
});
回答by arb
You can also use the .filter()
function as well here:
您也可以在.filter()
此处使用该功能:
$(document).ready(function () {
$('#report-area tbody tr').filter(function () {
return $.trim($(this).text()).length > 0;
}).addClass("my-class");
});
I like this because it's a little cleaner and limits the number of rows you need to iterate over.
我喜欢这个,因为它更简洁,并且限制了您需要迭代的行数。
回答by Sarfraz
I only want to add the class to the table row TR where the text was found.
我只想将类添加到找到文本的表行 TR。
You can do:
你可以做:
$('#report-area table tr').each(function(){
if ($.trim($(this).text()).length > 0) {
$(this).addClass("my-class");
}
});