【问题标题】:hide div if specific text is displayed in span如果特定文本显示在 span 中,则隐藏 div
【发布时间】:2016-08-22 10:22:02
【问题描述】:

如果特定文本显示在跨度中,我会尝试隐藏 div。我正在使用 jquery,这是代码:

HTML

<div class=“deliveryUpsellText”>
<p>blabla</p>
</div>


<ul>
  <li class=“error-msg”>
   <ul>
    <li>
     <span> Coupon Code “blabla” is not valid
     </span>
    </li>
   </ul>
  </li>
</ul>


<button type="button" id="cartCoupon" title="Apply Coupon" class="button applycouponhide" onclick="discountForm.submit(false) ; " value="Apply Coupon"><span style="background:none;"><span style="background:none;">Apply</span></span></button>

jQuery

$j('#cartCoupon').click(function(){
if($j(".error-msg span:contains('blabla')")){
    $j('.deliveryUpsellText').css({"display":"none"});
}

});

它会在点击时隐藏 div,但它会忽略 if 语句。因此,即使跨度中的文本是“猫”,它仍然会隐藏 div。谁能发现我做错了什么? 同样,由于#cartCoupon 按钮具有 onclick 事件dicountForm.submit(false);,deliveryUpsellText 在单击时被隐藏,但它未绑定到表单提交,因此一旦提交表单,它就会再次显示。有人知道我该如何解决吗?

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    jQuery 集合总是真实的(因为它是一个对象)。您需要检查它是否包含节点(选择的东西)。为此使用length 属性:

    if ($j(".error-msg span:contains('blabla')").length) {
        $j('.deliveryUpsellText').css({
            "display": "none"
        });
    }
    

    【讨论】:

    • $j('.deliveryUpsellText').toggle(!$j(".error-msg span:contains('blabla')").length)
    • 由于另一个原因对我来说不太适用,但我会接受它作为答案,因为通常它会像这样工作
    【解决方案2】:

    请试试这个

    $(document).ready(function () {
        $("#cartCoupon").click(function () {
            var errMsg = $(".error-msg ul li span").text();
            if (errMsg.search("blabla") >= 0) {
                $(".deliveryUpsellText").hide();
            }
        });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多