2016-08-22 73 views
4

如果特定文本在跨度中显示,则试图隐藏div。我使用jQuery,这是代码:如果在跨度中显示特定文本,则隐藏div

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"}); 
} 

}); 

它隐藏在点击的股利,但却忽略了if语句。所以即使跨度文本是“猫”,它仍然隐藏了div。任何人都可以发现我做错了什么吗? 也作为#cartCoupon按钮有onclick事件dicountForm.submit(false); deliveryUpsellText在点击时被隐藏,但它没有绑定到表单提交,所以它一旦表单提交后再次显示。任何人都知道我可以解决这个问题吗?

回答

1

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

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

或'附加$ J( 'deliveryUpsellText。')切换(附加$ J(! “错误味精跨度:包含( '布拉布拉')”)。长度)' – Rayon

+0

由于另一个原因,对我来说不太合适,但我会接受它作为答案,因为通常它会像这样工作 – MariaL

0

请试试这个

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

}); 
0

我想你要找的这个查询。它是为我工作

$(function(){ 
 
\t 
 
\t $('#cartCoupon').on('click', function(){ 
 
\t \t $('.error-msg').find('span').each(function(){ 
 
\t \t \t var text = $(this).text(); 
 
\t \t \t if(text.indexOf('blabla') >=0){ 
 
\t \t \t \t $(this).hide(); 
 
\t \t \t } 
 
\t \t }); 
 
\t }) 
 
});
<ul> 
 
    <li class="error-msg"> 
 
    <ul> 
 
    <li> 
 
    <span> Coupon Code “blabla” is not valid </span><br> 
 
    <span> Coupon Code is not valid </span><br> 
 
    <span> Coupon Code is not valid </span> 
 
    </li> 
 
    </ul> 
 
    </li> 
 
</ul> 
 
<button type="button" id="cartCoupon" title="Apply Coupon" class="button applycouponhide" value="Apply Coupon"><span style="background:none;"><span style="background:none;">Apply</span></span></button>