![](/img/trans.png)
[英]change background color of div if it contains an href that contains a specific string with jquery
[英]Change the color of a text in div using jquery contains
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>
可以這樣做:
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>"));
});
});
$("div:contains('bar')").each(function () {
$(this).html($(this).html().replace("bar", "<span class='red'>bar</span>"));
});
這肯定會奏效
請在這里看演示
你可以這樣使用:
$(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>'));
});
試試這個... 原型庫:
<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>
你可以這樣做。
$(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>
解決方案與代碼片段..
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.