jQuery文本html操作,以查找大量文本中出现的字符,然后更改其颜色

jQuery text html manipulation to find occurences of a char in a multitude of text then change it's color

本文关键字:文本 然后 字符 颜色 操作 html 查找 jQuery      更新时间:2023-09-26

我得到了这个HTML

    <div id="oops_menuHldrs" 
        style=" border-top:5px solid #ccc; position:absolute; width:100%;  background:#343434; bottom:0px; left:auto;">
          <div style="position:absolute; background:#343434; border-radius:10px; border:1px solid #CCC; right:0px; top:-20px;  padding:5px;">

<table id="opps_menu_links"  width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td><span><a href="../?abt=us">About us</a> black_text | black_text</span></td>
        <td><span><a href="../?ourA=gent">Our Agents</a> black_text | black_text</span></td>
        <td><span><a href="../contact=us">Contact us.</a> black_text | black_text </span></td>
      </tr>
    </table>

 </div>

我被告知,使用jQuery,选择所有|并赋予它们红色。

我尝试了类似的东西:

$('#opps_menu_links').html( 
        $('#opps_menu_links').text()
        .replace(/'|/,"<span style='color:#f00;'>|</span>"));

这会将所有内容转换为单个红色|

当然,如果没有jQuery,这很容易,只需给每个|穿上spans......但是,您将如何使用具有尽可能少代码的jQuery来做到这一点呢?

有什么帮助吗?

按如下方式更改脚本

http://jsfiddle.net/xHasy/

$('#opps_menu_links').html($('#opps_menu_links').html( ).replace(/'|/g,'<span style="color:red;">|</span>'));
一切都

是正确的,除了你忘记在正则表达式中放置全局匹配参数"g"

.replace(/'|/g,
//-----------^----place this

最终代码应为:

$('#opps_menu_links').html( 
        $('#opps_menu_links').text()
        .replace(/'|/g,"<span style='color:#f00;'>|</span>"));
    //---------------^----------place here

小提琴