2014-10-22 83 views
0

我需要檢查,如果裏面a標籤,包含檢查是否包含特定的文本

我使用這種代碼特定的文字,但它每次都返回成功消息。

if($('span.selectBox-label:contains("Segmentation")')){ 
    console.log('selected'); 
}else{ 
    console.log('not selected'); 
} 

這是我的HTML

<a class="selectBox required selectBox-dropdown selecterror selectBox-menuShowing" tabindex="NaN"> 
    <span class="selectBox-label" style="width: 293px;">List Management</span> 
    <span class="selectBox-arrow"></span> 
</a> 

回答

3

因爲$(selector)會返回一個jQuery對象,這將永遠是truthy。您可以檢查返回值的長度是否> 0或使用.is()

if ($('span.selectBox-label').is(':contains("Segmentation")')) { 
    console.log('selected'); 
} else { 
    console.log('not selected'); 
} 

還要注意的是,使用:contains()將返回部分匹配

+0

不錯...是有可能,每當文本內部跨度發生變化時執行此代碼? – 2014-10-22 10:23:50

+0

你將不得不看看突變觀察者/ evetns – 2014-10-22 10:25:49

0

使用

if($.trim(('span.selectBox-label').text()) == 'Segmentation'){ 
相關問題