2

所以我在这里想要完成的是改变受一些正则表达式影响的单词的颜色。

$(document).ready(function(){

  container = $("#modal_container section").text();
  hashtags = /\#\w+/g;
  var container_hash = container.match(hashtags);
  $(container_hash).css({'color':'red'}); 
  //We're grabbing the words, but how can I change the color?
  alert(container_hash);

 });

这是一个小提琴http://jsfiddle.net/vuDzC/2/让它更清楚。

谢谢

4

3 回答 3

5

您不能更改 textNodes/texts 的颜色,您应该用一个元素包装匹配的文本,然后设置该元素的样式。

$("#modal_container section p").html(function(_, html) {
   return html.replace(/(\#\w+)/g, '<span class="red">$1</span>');   
});

http://jsfiddle.net/vuDzC/4/

于 2013-04-20T23:10:27.253 回答
1

您正在寻找的这种做法(或者应该是一个足够好的例子):

<script type="text/javascript">
    $(document).ready(function(){
        var text = $("#modal_container").html();
        var myRegExp = new RegExp('\\#\\w+','gi');
        var newtext = text.replace(myRegExp,'<span style="color:red;">$&</span>');
        $("#empty").html(newtext);
    });
</script>
<div id="modal_container">
    #works<br />
    # Desnt Work<br />
    Not Even Close<br />
</div>
<div id="empty" style="margin-top:30px;">
</div>
于 2013-04-20T23:44:26.457 回答
0
 $(function(){

  var container = $("#modal_container section");
  var htmlWrappedHashtags = container.html().replace(/\(#\w+)/g, '<span class="red">$1</span>');
  container.html(htmlWrappedHashtags);

  $(".red").css({'color':'red'}); // or better: include ".red {color: red;}" into your CSS

 });
于 2013-04-20T23:14:04.407 回答