簡體   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