2012-11-27 85 views
0

我想修改父div的文本而不更改子div內容。如何更改父div的內容從子div?

我已經

<div id='testDiv'> 
    this is the test parent div 
    <div id='child1'> 
     lots of contents and child div 
     ................... 
    </div> 
    more div/child div and contents... 

</div> 
在我的jQuery

$('child1 div a').click(function(){ 
    $('#testDiv').text('new text'); //this will remove the child1 div and all the contents inside testDiv 
    //I want to replace 'this is the test parent div' text to 'newt text' 
}) 

是否有反正來完成這件事?非常感謝!

回答

1

如果你包裹在文本跨度,它會更容易改變它:

$('#testDiv').contents() 
      .filter(function(){return this.nodeType === 3}) 
      .wrap($('<span />',{'class':'test'})); 

$('.test').text('new text'); 

FIDDLE

如果span元素導致某種問題,您可以在文本節點發生更改後解開文本節點嗎?

+0

'{id:「test」}'是一個壞主意。改用類。 – VisioN

+0

@VisioN - 這只是一個展示如何訪問包裝範圍的基本方法,並且與類/標識符的討論無關? – adeneo

+0

這段代碼並不是完全透明的,當然,明確指出需要改變的那段文本會更有意義嗎?畢竟,如果它是可識別的,它必須有一些語義含義,所以標記應該反映這一點。 – Nick

-2

你只需要包含直接...

<div id='testDiv'> 
    <div id='changeMe'> 
     this is the test parent div 
    </div> 
    <div id='child1'> 
     lots of contents and child div 
     ................... 
    </div> 
    more div/child div and contents... 
</div> 

了jQuery要改變到另一個DIV和目標的部分:

$('child1 div a').click(function(){ 
    $('#changeMe').text('new text'); 
}) 
+0

任何人都願意解釋爲什麼他們認爲是一個壞主意/將無法正常工作? – Nick

+0

你沒有足夠重視這個問題的要求,是我的猜測。在你的例子中,'changeMe'是** not **'child1'的'parent div',所以你的代碼明確*不會*這個問題要求什麼。 –

+0

我也這麼認爲,但問題是如何在不更改子div內容的情況下修改父子div中的文本。它並沒有說父母的div不能被修改.'changeMe'不是父母的div,但它是父母div的孩子。 – Nick

2

嘗試使用.filter()混合和.contents()

$('#child1 div a').click(function() { 
    $('#testDiv').contents().filter(function() { 
     if (this.nodeType != 1 && this.data.trim() != '') { 
      return this.data = 'New Text'; 
     } 
     else { 
      return this 
     }; 
    }); 
})​ 

Check Fiddle