2014-10-22 86 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'){ 
相关问题