0

示例 HTML:

<div>
    <input></input>
    Change me
</div>
  1. 如何将我的文本更改Change meAnother text

  2. 我怎样才能附加一些Change me文本Change me please

我知道只有我可以附加一些带有元素的文本,例如..

var new_text = "<span>please</span>";
$(new_text).appendTo("div");

但是我怎么能在没有任何元素的情况下追加<span>

游乐场 + 测试:http: //jsfiddle.net/yU4Qj/

4

3 回答 3

3

You can iterate over the .contents() of your <div> until you find the required text node, whose contents you can then modify by altering its .nodeValue property.

$('div').contents().each(function() {
    if (this.nodeType === 3 && this.nodeValue.match(/Change/)) {
        this.nodeValue = "I've been changed!";
    }
});

A better solution though would be to wrap the original text node in a <span> so that you can access it directly via DOM selectors. You could perform that wrapping automatically (i.e. using JS code, not by changing the source) when the page is first loaded, and then use normal jQuery selectors and methods.

于 2013-04-11T08:18:30.057 回答
1

there are so many ways you can do to achieve it... one way is this...

var new_text = "please";
$('div').html(function(i,h){
return h + new_text;
});

demo

于 2013-04-11T08:20:18.430 回答
1
$('div').contents().filter(function() {; return this.nodeType == 3; }).replaceWith('I have changed')
于 2013-04-11T08:21:57.330 回答