【问题标题】:Case insensitive searching for a string in DOM在 DOM 中搜索不区分大小写的字符串
【发布时间】:2013-11-20 10:14:25
【问题描述】:

我正在遍历每个文本节点,并寻找搜索字符串是否在该文本节点中可用。如果它存在,我将围绕 span 节点进行突出显示。示例代码可在此链接获得:.http://jsfiddle.net/LcRDz/

现在如果用户给出一个词,它只会搜索那个词。 无论大小写如何,我都需要在 DOM 中搜索单词。例如,如果我的搜索词是 the,它应该突出显示词 The, THE, the

【问题讨论】:

    标签: javascript dom search case-insensitive


    【解决方案1】:

    在使用indexOf 检查之前,对两个值都使用toLowercase,使比较不区分大小写。

     //Notice both n.nodeValue and word are sent to lowercase.
     for (var i;
            (i = n.nodeValue.toLowerCase().indexOf(word.toLowerCase(), i)) > -1; 
               n = after) {
                 var after = n.splitText(i + word.length);
                 var highlighted = n.splitText(i);
                 var span = document.createElement('span');
                 span.className = "spanClass";
                 span.style.backgroundColor = "red";
                 span.appendChild(highlighted);
                 after.parentNode.insertBefore(span, after);
             }
    

    JS FIDDLE: http://jsfiddle.net/LcRDz/2/

    【讨论】:

      【解决方案2】:

      你应该通过修改来解决

      for (var i;
          (i = n.nodeValue.indexOf(word, i)) > -1; n = after) 
      

      for (var i;
          (i = n.nodeValue.toLowerCase().indexOf(word.toLowerCase(), i)) > -1; n = after) 
      

      【讨论】:

      • word 也应该小写
      【解决方案3】:

      在 highlightWords 方法中从

      更改你的 for 循环

      原文:

      for (var i;
                   (i = n.nodeValue.indexOf(word, i)) > -1; n = after)
      

      新:

      for (var i;
                   (i = n.nodeValue.toLowerCase().indexOf(word.toLowerCase(), i)) > -1; n = after)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-05
        • 2011-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-07
        • 2018-09-29
        相关资源
        最近更新 更多