繁体   English   中英

更改文本节点文本

[英]Change text-nodes text

如何更改文本节点的文本?

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更改文本吗?

使用文本节点的nodeValuedata属性。 两者同等有效且受到良好支持:

$textNodes.each(function() {
    this.data = "CHANGED";
});

顺便说一句, Node.TEXT_NODE中不存在Node.TEXT_NODE ,所以最好只使用3

您无法使用jQuery直接编辑文本节点。

只需直接在节点上使用本机datanodeValue属性。

$textNodes.each(function() {
    this.data = "Hello world";
 // this.nodeValue = "Hello world";
});

jsFiddle

经过很长时间在MDN中找到它:

由于某些愚蠢的原因,此属性称为nodeValue not value ...

固定的JQuery:

var $textNodes = $('.theClass').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).each(function(){
    this.nodeValue = "hello World";
});

修复了JSFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM