1

在下面的代码中,我想使用 jQuery 仅将单词“Going for”更改为“Highest bid:”。我知道如何使用的唯一方法是replaceWith生成这样的东西:$('#wp-bidcontainerleft').replaceWith('new word');但这行不通,因为我没有替换 div 中的所有内容。

<div id="wp-bidcontainerleft">
  Going for
  <br>
  $101.00
</div>

实现这一目标的最简单方法是什么?

4

3 回答 3

1

您必须 get .contents()which 还检索纯文本子元素,然后替换第一个子元素

$('#wp-bidcontainerleft').contents().eq(0).replaceWith(document.createTextNode('Highest bid:'));
于 2012-11-14T10:06:59.057 回答
0

试试这个方法

$(function () {
    $('#wp-bidcontainerleft').each(function() {
        var text = $(this).text().replace('Going for', 'Highest bid:');
        $(this).text(text);
    });
});
于 2012-11-14T10:18:25.500 回答
0

您可以使用contents方法:

$('#wp-bidcontainerleft').contents().each(function(i, v){
    if (i === 0) {
        this.textContent
        ? this.textContent = 'new word' // non-ie browsers
        : this.innerText = 'new word';  // crazy ie
        return false // stop executing each method
    }
})

http://jsfiddle.net/DPVTg/

于 2012-11-14T10:20:02.570 回答