2012-11-27 48 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