Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在匹配文本上应用CSS_Javascript_Jquery - Fatal编程技术网

Javascript 在匹配文本上应用CSS

Javascript 在匹配文本上应用CSS,javascript,jquery,Javascript,Jquery,我试图应用一个类,其中文本与同级元素匹配 我的特定条件是: 我有一个包含多行的表,它基于我通过数据库获得的数据。 其中一个td元素具有我定义的类。 现在,我只想在这个元素的文本与另一个元素匹配的td元素上应用一个类 因此,如果td的html/text相等,它就具有该类 我试过: $('#table tbody>tr').find('td[class^="customtd"]').each(function() { if($(this).html().trim() == $(this

我试图应用一个类,其中文本与
同级元素匹配

我的特定条件是:

我有一个包含多行的表,它基于我通过数据库获得的数据。 其中一个
td
元素具有我定义的类。 现在,我只想在这个元素的文本与另一个元素匹配的
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');
    }
});

您必须迭代每个同级
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");
});

必须设置要搜索的值,然后遍历所有表数据。如果找到匹配项,请添加特定类

此外,您应该在jQuery中缓存变量,并避免使用每个()函数,因为与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');
    }
}
//缓存正在搜索的元素
var search=$('.customtd').html().trim();
//缓存整个表,以便使用for循环
var table=$(“#table tbody>tr>td”);
//使用for循环可获得更高的性能
对于(变量i=0;i
以下是一个工作示例: