5

这里 div 中的整个文本都变成了红色。但我只需要更改“条”字颜色

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
      <title> new document </title>
     <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
     <script type="text/javascript">
        $(document).ready(function(){
            $("#foo:contains('bar')").css('color','red');
        });
     </script>
     </head>
     <body>
    <div id="foo">
        this is a new bar 
    </div>
     </body>
    </html>
4

6 回答 6

7

可以这样做:

http://jsfiddle.net/PELkt/

var search = 'bar';
$(document).ready(function () {
    $("div:contains('"+search+"')").each(function () {
        var regex = new RegExp(search,'gi');
        $(this).html($(this).text().replace(regex, "<span class='red'>"+search+"</span>"));
    });
});
于 2013-06-21T10:35:04.973 回答
6
$("div:contains('bar')").each(function () {
    $(this).html($(this).html().replace("bar", "<span class='red'>bar</span>"));
});

这肯定会奏效

请在此处查看演示

于 2013-06-21T10:32:24.630 回答
2

您可以使用这种方式:

       $(document).ready(function(){
               //  $("#foo:contains('bar')").css('color','red');
               var text = 'bar' ;
               var  context = $("#foo").html();
               $("#foo").html(context.replace(text,'<span style="color:red;">'+text+'</span>'));
        });
于 2013-06-21T10:36:57.077 回答
2

试试这个......原型库:

<html> 
<head> 

    <style type="text/css">
        #content span {
            background-color: yellow;
        }
    </style>
    <script type="text/javascript" src="prototype.js"></script>
    <script type="text/javascript">
        Event.observe(window,'load',function(){
            var htm = $('content').innerHTML;
            $('content').innerHTML = htm.sub('bar','<font color=red>bar</font>');
        });
    </script>
</head>
<body>

    <div id="content">
        this is a new bar
    </div>

</body>

于 2013-06-21T10:41:59.277 回答
1

你可以这样做。

$(document).ready(function(){
    var matchingTest = 'demo';
    $("#container:contains("+matchingTest+")").each(function () {
	    $(this).html($(this).html().replace(matchingTest, "<span class='red'>"+matchingTest+"</span>"));
    });
});
.red{
  background:#eada93;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container">
  Hello this is a demo contents.
</div>

于 2017-01-07T05:12:50.940 回答
0

带有代码段的解决方案..

var text_change = 'bar';
$(document).ready(function () {
    $("div:contains('"+text_change+"')").each(function () {
        var regex = new RegExp(text_change,'gi');
        $(this).html($(this).text().replace(regex, "<span class='red'>"+text_change+"</span>"));
    });
});
.red {
    color:#008000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">this is a new bar and bar.</div>

于 2017-01-07T05:19:26.440 回答