【问题标题】:JQuery Find and change style of a stringJQuery 查找和更改字符串的样式
【发布时间】:2015-10-01 18:46:18
【问题描述】:

我需要编写一个函数,它会在我的 HTML 页面中的所有内容中搜索特定字符串,如果找到,则更改文本的颜色。

这可能吗?

谢谢

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    你可以这样做:

    CSS:

    .someclass {
        color: red;
    }
    

    Javascript:

    $('p:contains('+yourstring+')', document.body).each(function(){
      $(this).html($(this).html().replace(
            new RegExp(yourstring, 'g'), '<span class=someclass>'+yourstring+'</span>'
      ));
    }​);​
    

    请注意,如果您的字符串在标签或属性中,这会产生问题。

    Demonstration

    在将处理程序附加到段落(或其中可能包含您的字符串的元素,例如链接)之前,请小心运行此代码。

    【讨论】:

    • 这不会包装包含字符串的整个 div,而不仅仅是字符串本身吗?
    • @JuanMendes 我不确定你的意思。我添加了一个演示
    • 我错了...但是,这种方法的缺点是它会覆盖 HTML,因此如果您在被替换的节点上有任何处理程序,您已经删除了它们。理想情况下,您会找到文本范围并从中创建一个节点。
    • 是的。我已将其更改为针对 P 元素。这也避免了其他问题。
    【解决方案2】:

    dystroy 的答案的问题是它会覆盖整个 HTML,因此如果您在包含文本的节点中有任何处理程序,它们将被删除。

    正确的解决方案是使用text ranges 只更新文本本身,而不是它周围的所有HTML。见Highlight text range using JavaScript

    为了好玩,有一个内置方法window.find 可以在FF and Chrome 中使用。但它不在标准中,一次只能找到一个。就像 ctrl+f 一样。

    window.find("anything");
    

    【讨论】:

      【解决方案3】:

      JQuery Find and change style of a string >> Only Copy Paste and run :)

        $('#seabutton').click(function()
              {
                  var sea=$('#search').val();
                  var cont=$('p').val();
                  alert(cont);
                  $('p:contains('+sea+')').each(function()
                       {
          /*          $(this).html($(this).html().replace(new RegExp(sea, 'g'),'<span class=someclass>'+sea+'</span>'));
           */            $(this).html($(this).html().replace(
                              new RegExp(sea, 'i'), '<span class=someclass>'+sea+'</span>'
                        )); 
                  });
      
              });
              $('p').click(function()
              {
                  $(".someclass").css("color", "black");
              });
              $('#search').blur(function()
              {
                  $(".someclass").css("color", "black");
      
              });
      
          })
      
      
          </script>
          <style type="text/css">
          .someclass {
              color: red;
          }
          </style>
          </head>
          <body>
          <!-- Select Country:<select id="country" name="country">
          </select>
          <table id="state" border="1">
      
      
          </table> -->
          <br>
          Enter Text:<input type="text" id="search"/><input type="button" id="seabutton" value="Search"/>
          <div id="serach">
          <p>This is ankush Dapke
          </p>
      
          </div>
          </body>
          </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-16
        • 1970-01-01
        • 2018-10-17
        相关资源
        最近更新 更多