javascript - 如果存在元素 ID,则隐藏其他元素

标签 javascript jquery

我有一个电子商务网站,该网站对给定商品有多个价格。如果页面上存在较低的价格等级,我正在尝试设置一些隐藏价格的脚本。

<table>
    <tbody>
        <tr>
            <td>
                <font>
                    <div class="product_listprice">199.99</div>
                </font>
                <font>
                    <div class="product_productprice">179.99</div>
                </font>
                <b>
                    <div class="product_saleprice">159.99</div>
                </b>
                <font>
                    <div class="product_discountprice">139.99</div>
                </font>
            </td>
        </tr>
    </tbody>
</table>

基本上我需要的是一个脚本,如果页面上存在 .product_saleprice,它将隐藏 .product_productprice,如果 .product_discountprice 存在,它将隐藏 .product_saleprice 和 .product_productprice。

这是我到目前为止通过一些谷歌挖掘得出的结论。

<script type="text/javascript">
    $(document).ready(function(){
        if ( $(".product_discountprice").size() )
        $(".product_saleprice, .product_productprice").hide();
        });
    });   
</script>

然而,它似乎并没有起作用。有任何想法吗?我是 jquery 新手,所以我确信有更好的方法可以做到这一点......

最佳答案

// Essentially what I need is a script that will hide .product_productprice
// if .product_saleprice exists on the page...
if ($('.product_saleprice').length) {
    $('.product_productprice').hide();
}

// ...and will hide both .product_saleprice and .product_productprice
// if .product_discountprice exists.
if ($('.product_discountprice').length ) {
    $('.product_saleprice, .product_productprice').hide();
}

添加新类名的更新,而不是隐藏:

if ($('.product_saleprice').length) {
    $('.product_productprice').addClass('some-class');
}

if ($('.product_discountprice').length ) {
    $('.product_saleprice, .product_productprice').addClass('some-class');
}

关于javascript - 如果存在元素 ID,则隐藏其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26243515/

相关文章:

jquery 展开/切换 - 初始 div 大小

javascript - 解决嵌套 Promise 后运行函数

javascript - 如何在angularjs中调试$http方法

javascript - jQuery 定义函数未选择

javascript - jquery "empty"改变滚动条

javascript - 如何将数据表内容存储在本地存储中

javascript - 显示/隐藏附加元素内的输入字段

javascript - 从服务器端调用 Javascript 代码是一种好习惯吗?

javascript - 在 js 文件中为网络故障覆盖 "Error Loading Page"

jquery - 在鼠标悬停时更改 css 类