0

我正在尝试从子 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' 
})

有没有办法完成这件事?非常感谢!

4

4 回答 4

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
        };
    });
})​

检查小提琴

于 2012-11-27T23:07:33.237 回答
2

您可以使用firstChild属性:

​document.getElementById('testDiv').firstChild.nodeValue = 'new text'​​;

http://jsfiddle.net/vstHS/

于 2012-11-27T23:09:09.687 回答
1

如果将文本包装在跨度中,则更改它会更容易:

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

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

小提琴

如果 span 元素导致某种问题,您当然可以在 textnode 更改后展开它?​</p>

于 2012-11-27T22:59:48.833 回答
-2

您只需要包含要更改为另一个 div 的部分并直接定位它...

<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:

$('child1 div a').click(function(){
    $('#changeMe').text('new text');
})
于 2012-11-27T22:57:18.250 回答