如何更改文本节点文本?
HTML:
<p class='theClass'> bbb <a href=#> foo</a> aaa </p>我正在尝试将“aaa”和“bbb”更改为hello world。我成功地选择了这些节点,但无法更改它们的文本。
到目前为止Jquery:
var $textNodes = $('.theClass').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
});JSFiddle
如何使用此$textNodes更改他们的文本?
发布于 2012-01-31 21:41:37
使用文本节点的nodeValue或data属性。两者都是有效的,并且都得到了很好的支持:
$textNodes.each(function() {
this.data = "CHANGED";
});顺便说一句,IE < 9中不存在Node.TEXT_NODE,所以您最好改用3。
发布于 2012-01-31 21:41:33
不能使用jQuery直接编辑文本节点。
只需在节点上直接使用原生data或nodeValue属性即可。
$textNodes.each(function() {
this.data = "Hello world";
// this.nodeValue = "Hello world";
});jsFiddle
发布于 2012-01-31 21:44:45
在MDN中花了很长时间才找到的
由于一些愚蠢的原因,这个属性被称为nodeValue而不是value。
固定JQuery:
var $textNodes = $('.theClass').contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).each(function(){
this.nodeValue = "hello World";
});固定JSFiddle
https://stackoverflow.com/questions/9080407
复制相似问题