2013-03-14 62 views
0

節點我有HTML這樣的:更新「文本」與jQuery

<label><input type="radio" /> Lorem</label> 

有什麼改變「排版」到「存有」的最佳方式?這些不工作:

// nope: 
$('input').next().text('Ipsum'); 

// also nope: 
var text = $('input').parent()[0].childNodes[1]; 
$(text).text('Ipsum'); 

我可以很容易地更改HTML到:

<label><input type="radio" /><span> Lorem</span></label> 

或直接使用replaceWholeText DOM方法:

$('input').parent()[0].childNodes[1].replaceWholeText(' Ipsum'); 

或任意數量的其他事情,但我想知道是否有一個乾淨的jQuery方式來做到這一點。

回答

1

醜陋的方式:

$('input').parent().contents().each(function(){ 
    if(this.nodeType === 3) 
    this.nodeValue= "Ipsum"; 
}); 

或者更好:

$('input')[0].nextSibling.nodeValue = "Ipsum"; 
1

的jQuery沒有任何一流的文本節點的支持。您可以:

$("input")[0].nextSibling.nodeValue = "Ipsum"; 

或使用<span>標識符或類和目標。如果您需要動態更改文本,則可能需要這樣的容器。