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

3

我有一个电子商务网站,对于同一件商品有多个价格。我正在尝试设置一个脚本,如果页面上存在较低价格,则隐藏一个价格。

<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 新手,所以肯定有更好的方法……


4
"<font>"?1990年代打电话来要回它的HTML了。 - Marc B
请告诉我,如果您有任何疑虑或意见,请发送至www.volusion.com。 - Alex Ritter
@MarcB 你应该意识到当前最终版本的HTML(4)最初是在1990年代发布的 :) - Mathew Thompson
应该将.size()改为.length - tymeJV
@tymeJV 这不是问题所在,size() 也可以很好地工作。 - hakazvaka
3个回答

4
// 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');
}

.size().length是相同的。 - dfsq
是的,这修复了我已经想出来的那一部分。然而,这只会隐藏折扣价格存在的情况。如果折扣价格不存在,我该如何“加倍隐藏”呢? - Alex Ritter
基本上,如果只有销售价格和产品价格,我还需要它有条件地隐藏。 - Alex Ritter
1
@dfsq 我从未说过 .size() 是有问题的,我只是鼓励使用非弃用的方法。弃用通常意味着在将来的某个时候会被移除,在那时它就会出现问题。 - jmar777
显示剩余5条评论

0

http://jsfiddle.net/3481uqa4/1/

  if ($(".product_discountprice").length) {
        $(".product_productprice, .product_saleprice").hide();       
    } else if ($(".product_saleprice").length) {
        $(".product_productprice").hide();
    }

如果存在product_discountprice,则隐藏产品价格和销售价格,否则如果存在销售价格,则隐藏产品价格。如果两者都不存在,则显示产品价格。


-1

试试这个... 不确定是否正确。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接