我想更改HTML元素的文本,但是用jQuery保留其余的内部html。
例如:
<a href="link.html">Some text <img src="image.jpg" /></a> 将“某些文本”改为“其他文本”,其结果应该如下:
<a href="link.html">Other text <img src="image.jpg" /></a> 编辑:我的当前解决方案如下:
var aElem = $('a');
var children = aElem.children();
aElem.text("NEW TEXT");
aElem.append(children); 但一定有更优雅的方法来做这件事。
发布于 2011-03-08 13:20:41
由于您无法修改链接,所以可以选择使用replace
$("a").html($("a").html().replace("Some text", "Other text"));小提琴上的示例。
发布于 2011-03-08 13:09:41
包装要在跨度内更改的文本。
<a href="link.html"><span>Some text</span> <img src="image.jpg" /></a>
$('a span').html( 'new text' );发布于 2014-12-05 10:03:23
另一种方法是按以下方式使用contents()方法:
给定的
<a href="link.html">Some text <img src="image.jpg" /></a>您可以用'Some text'替换jQuery
var text = $('a').contents().first()[0].textContent;
$('a').contents().first()[0].textContent = text.replace("Some text", "Other text");jsFiddle示例这里。
contents()的想法是受这问题的启发,由用户charlietfl回答。
https://stackoverflow.com/questions/5232862
复制相似问题