javascript 如果 <td> 包含“a”,则将 <tr> 背景设为红色,但 each() 会变慢

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11414427/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:07:26  来源:igfitidea点击:

If a <td> contains "a" then make the <tr> background red but the each() is to slow

javascriptjquery

提问by Hello-World

How do you write this so it runs faster. It looks like because I'm using an each() it is slowing it down.

你怎么写这个让它运行得更快。看起来是因为我正在使用 each() 它正在减慢它的速度。

Can I use filter()?

我可以使用过滤器()吗?

 $("#X tr").each(function () {       
     if ($(this).find("table td:eq(1)").text() == "a") {
         $(this).css("background":"red");    
  }

});   

     <table id = "X">
        <tr >
        <td>a</td>
        <td>b</td>
        <td>c</td>
        </tr>
        <tr >
        <td></td>
        <td></td>
        <td></td>
        </tr>
        ...
        <tr >
        <td>a</td>
        <td>b</td>
        <td>c</td>
        </tr>
   </table>

thanks

谢谢

采纳答案by pimvdb

You can use the :containsselector: http://jsfiddle.net/Af6Nz/1/.

您可以使用:contains选择器:http: //jsfiddle.net/Af6Nz/1/

?$("#X tr:contains('a')").css("background-color", "red");??????????????????????????????

回答by David says reinstate Monica

I'd suggest:

我建议:

$('td:contains("a")').closest('tr').css('background-color','red');

JS Fiddle demo.

JS小提琴演示

Or, in to affect allancestor trelements:

或者,要影响所有祖先tr元素:

$('td:contains("a")').parents('tr').css('background-color','red');

JS Fiddle demo.

JS小提琴演示

Or to affect all trelements with descendent (however deeply nested):

或者影响所有tr具有后代的元素(但嵌套很深):

$('tr').filter(
    function(){
        return $(this).find('td:contains("a")').length;
    }).css('background-color','red');

JS Fiddle demo.

JS小提琴演示

Added a function, lookAt()that might be used instead:

添加了一个函数,lookAt()可以用来代替:

function lookAt(haystack, needle) {
    if (!haystack) {
        return false;
    }
    else {
        needle = needle ? needle : 'a';
        for (var i = 0, len = haystack.childNodes.length; i < len; i++) {
            var cur = haystack.childNodes[i];
            if (cur.nodeType == 3 && cur.nodeValue.indexOf(needle) > -1){
                return true;
            }
            else if (i == (len-1)) {
                return false;
            }
        }
    }
}

$('#table td').filter(
    function() {
        return lookAt(this);
    }).css('background-color', 'red');?

JS Fiddle demo

JS小提琴演示

JS Perf test examining the lookAt()function approach against the return $(this).is(':contains("a")')Sizzle-based approach.

JS Perf 测试检查基于 Sizzle 的方法的lookAt()函数return $(this).is(':contains("a")')方法

For reference, for a closer comparison the JS Perf jQuery test was the following:

作为参考,为了更仔细的比较,JS Perf jQuery 测试如下:

$('#table td').filter(
    function() {
        return $(this).is(':contains("a")')
    }).css('background-color', 'red');?

JS Fiddle demo.

JS小提琴演示

回答by Denys Séguret

Using containsand parent(to go back to the trthat we want to colorize) :

使用containsparent(回到tr我们想要着色的那个):

$(this).find('td:eq(0):contains("a")').parent().css("background","red");

or using has:

或使用

$(this).find('tr:has(td:eq(0):contains("a"))').css("background","red");

If you don't need the eqcondition, use

如果您不需要eq条件,请使用

$(this).find('td:contains("a")').parent().css("background","red");

Keep in mind that eqis 0-based (as your test case didn't involve a matching element with 1 instead of 0).

请记住,eq是基于 0 的(因为您的测试用例不涉及带有 1 而不是 0 的匹配元素)。

Demonstration : http://jsfiddle.net/KRqQN/

演示:http: //jsfiddle.net/KRqQN/

回答by RobG

If you're concerned about performance, the following might help.

如果您担心性能,以下内容可能会有所帮助。

var getText = (function() {
  var div = document.createElement('div');

  if (typeof div.textContent == 'string') {
    return function (el) {
      return el.textContent;
    };

  } else if (typeof div.innerText == 'string') {
    return function (el) {
      return el.innerText;
    };
  }
}());

function foo(table) {
  var row, rows = table.rows;
  var i = rows.length;
  var re = /a/;

  while (i--) {
    row = rows[i];

    if (re.test(getText(row))) {
      row.style.backgroundColor = 'red';
    }
  }
}