使用jQuery从代码中删除字符

时间:2014-04-14 11:21:38

标签: javascript jquery

我试图从预先制作的代码段中删除em破折号。但是,它嵌入在树中,我似乎无法访问它:

jsFiddle

HTML:

  <span class="price">           
        <span class="price">
            <span class="amount">£8.75</span>
            – // I need this!
            <span class="amount">£19.20</span>
        </span>
    </span>

JS:

$('span.price').each(function(){
    $(this)
        .find('.amount')
        .next()
        .remove()

    var c = $(this);
    var t  = c.text();
    var b = t.replace('—', '@'); // but if i use ('£', '@') it replaces the pound sign
    c.text(b);

});

有谁知道上面为什么找不到并取代&#39; - &#39;冲?

6 个答案:

答案 0 :(得分:4)

您可以使用.contents().filter的组合来查找内容为-的所有文本节点并将其删除:

$(".price").contents().filter(function() {
    return this.nodeType == 3 && $.trim(this.textContent) === "–";
}).remove();

jsFiddle

编辑:更改为使用jQuery修剪而不是ES5,因为这将适用于&lt; IE9

答案 1 :(得分:2)

有趣的事:) 我将jsfiddle的html部分中的“ - ”复制到你的代码中

var b = t.replace("–", '@');

现在替换确实有效。 :)

http://jsfiddle.net/bhAtn/7/

答案 2 :(得分:1)

DEMO

尝试下面的代码,它会起作用

$('span.price').each(function(){
    $(this)
        .find('.amount')
        .next()
        .remove()
    .end();
    var c = $(this);
    var t  = c.text();
    var b = t.replace(/–/g, ' ');
    c.text(b);

});

答案 3 :(得分:1)

这很简单,只是出于你的特定目的,但有诀窍......

$('span.price > span.price').each(function(){
    var $this = $(this);
    $this.html($this.html().replace("–", ""));
});

<强> jsfiddle example

答案 4 :(得分:1)

您可以只获取元素内容过滤器文本节点并将其删除。

代码:

$('span.price').each(function () {
    $(this)
        .contents()
        .filter(function () {
        return this.nodeType == 3; //Node.TEXT_NODE
    }).remove();

});

演示:http://jsfiddle.net/IrvinDominin/fSMKL/

答案 5 :(得分:1)

您可以使用以下内容:

$('span.price span.amount').each(function(){
    if (this.nextSibling) {
        this.nextSibling.nodeValue = this.nextSibling.nodeValue.replace(/—/g,'');
    }
})
相关问题