Jquery:从文本节点获取文本

Jquery: get text from text node

本文关键字:获取 取文本 节点 文本 Jquery      更新时间:2023-09-26

我有很多div,我想让它们在售价为0.00美元时消失

<div class="ProductPriceRating">
    <em>
         <strike class="RetailPriceValue">$79.99</strike> 
         $0.00
    </em>
    <span class="Rating Rating0">
        <img src="..." alt="" style="display: none" />
    </span>
</div>
所以我写了这个jquery
$(function(){
    $(".ProductPriceRating em").contents().filter(function() {
        return this.nodeType != 1; 
    }).wrap("<span></span>");
    console.log($(".ProductPriceRating em span").text());
    if($(".ProductPriceRating span").text() == ' $0.00'){
            console.log('success');
        $('div.ProductPriceRating').hide();
        $('div.ProductActionAdd').hide();
    }
});

我在文本节点周围包装了一个span标记,使其更容易访问。然后我控制台记录它并得到"$0.00 $0.00 $0.00"(页面上的每个元素都有一个"$0.00")。但没有成功。

我就是不知道哪里出错了

你需要遍历每个父元素:

来自:

if($(".ProductPriceRating span").text() == ' $0.00'){
        console.log('success');
    $('div.ProductPriceRating').hide();
    $('div.ProductActionAdd').hide();
}

:

$(".ProductPriceRating").each(function() { 
    if($(this).find('span').text() == ' $0.00'){
            console.log('success');
        $(this).hide();
        $('div.ProductActionAdd').hide();
    }
});

在if语句中只有

$(".ProductPriceRating span").text()

在console.log中,有

$(".ProductPriceRating em span").text()

这可能是问题所在,因为还有一个span的class "Rating"