我正在尝试应用文本与sibling
元素匹配的类。
我的确定条件是:
我有一个基于我通过数据库获取的数据的多行表。 其中一个
td
元素具有我定义的类。 现在我想只在这个元素的文本与另一个元素匹配的td
元素上应用一个类。
所以,就像html/text
相等的那个人一样。
我试过了:
$('#table tbody>tr').find('td[class^="customtd"]').each(function() {
if($(this).html().trim() == $(this).siblings('td').html().trim()) {
$(this).addClass('active');
}else {
$(this).removeClass('active');
}
});
答案 0 :(得分:3)
你必须迭代每个兄弟td
(或使用filter
),检查文本匹配,然后添加类:
$('#table tbody>tr').find('td[class^="customtd"]').each(function() {
var text = $(this).text();
$(this).siblings("td").filter(function() {
return $(this).text() == text;
}).addClass("active");
});
答案 1 :(得分:1)
您必须设置要搜索的值,然后遍历所有表数据。如果找到匹配项,请添加特定类。
此外,您应该在jQuery中缓存变量并避免使用each()函数,因为与for循环相比,它的性能非常差。
//cache the element you are searching for
var search = $('.customtd').html().trim();
//cache the whole table so we can use a for loop
var table = $('#table tbody>tr>td');
//use for loop for more performance
for (var i = 0; i < table.length; i++) {
if(table.eq(i).html().trim() == search) {
table.eq(i).addClass('active');
}else {
table.eq(i).removeClass('active');
}
}
这是一个有效的例子: