<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>上面的代码将添加下划线到包含"John".But的整个DIV中,如何才能只给"John“加下划线。
请谁来帮帮我。
发布于 2011-08-23 22:22:14
您必须在span中对文本进行换行:
$("div:contains('John')").each(function()
{
var $el = $(this);
$el.html( $el.html().replace(/John/g, '<span style="text-decoration: underline">John</span>') );
});http://jsfiddle.net/GP96T/2/
正如@布拉德·克里斯蒂所指出的,只有当你知道你的属性中没有"John“,或者div没有孩子的时候,你才应该使用它。
发布于 2011-08-23 22:22:42
相反,您可以:
$oldcontent = $("div:contains('John')").html();
$("div:contains('John')").html($oldcontent.replace('John', '<u>John</u>');发布于 2011-08-23 22:22:55
Hackish的方式:
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
<script>
$("div:contains('John')").each(function(i,e){
var $this = $(this);
var html = $this.html()
.replace(/John/g,'<span style="text-decoration:underline;">John</span>');
$this.html(html);
});
</script>如图所示,here
但要小心,如果在链接或title标记中有"John“,这也将替换这些实例。例如:
<div><img src="..." title="This is John" /></div>变成:
<div><img src="..." title="This is <span style="text-decoration:underline;">John</span>" /></div>(我想这是不可取的)
https://stackoverflow.com/questions/7162494
复制相似问题