-4

此演示代码循环 3 次,每次都附加文本。我需要的是文本不会被附加而是被替换,因此在添加新文本之前应该删除以前附加的文本。我已经尝试了很多东西,没有任何效果。

编辑:您不能在跨度之后添加额外的标签!

 <div>
     <span id="i_1">this is </span>
</div>
​
var i = 3;
while(i>0)
{
     //// how to remove the text added on the previous iteration?
    $("#i_1").after('text');
    i--;
}
​

http://jsfiddle.net/pHYHW/

4

6 回答 6

3

小菜一碟,这就是jQuery afterText 插件的用途。

Example/Demo:

<div>
  <span id="i_1">this is </span>
</div>
​
var i = 3;
while (i)
{
    $("#i_1").afterText('text');
    i--;
}

jQuery afterText Plugin on github

于 2012-06-21T12:46:44.717 回答
2
var i = 3;
while ( i ) {
    $("#i_1")[ 0 ].nextSibling.nodeValue = 'text';
    i--;
}

Demo: http://jsfiddle.net/Ralt/pHYHW/7/

There you go, enjoy. You can also use data instead of nodeValue if you prefer.

By the way, this works because nextSibling is a textNode, thus the nodeValue property is available.

于 2012-06-21T12:59:42.980 回答
0

不要在元素之后放置文本,而是修改 HTML 以包含一个包含文本的元素:

<span id="i_1">this is </span> <span id="value"></span>

只需设置另一个元素的文本:

for (var i = 3; i > 0; i--) {
    $("#value").text('text');
}
于 2012-06-21T02:18:49.023 回答
0

这有效:

var i = 3;
var old_text = $('#i_1').html();
while(i>0)
{
    $("#i_1").html(old_text + 'text');
    i--;
}

演示在: http: //jsfiddle.net/2DcXe/ ​</p>

于 2012-06-21T02:20:11.300 回答
0

我不确定这是否是你要找的,但试试这个:

HTML

<div>
    <span id="i_1">this is </span><span id="i_2"></span>
</div>

​</p>

Javascript

var i = 3;
while(i>0)
{
    $("#i_2").html('text');
    i--;
}
于 2012-06-21T02:24:52.417 回答
0

Well it's not jQuery but here is how I would do it...

var ele = document.getElementById('i_1'); // get the element
var tn = ele.nextSibling, // get it's next sibling (picks up text nodes)
    mode = 'textContent' in ele ? 'textContent' : 'innerText'; // ( ie is smelly )
for (var i = 3; i > 0; i--) {
    tn[mode] = "Text"; // change the text content. 
}

Here is the Demo

于 2012-06-21T13:01:57.823 回答