2012-07-12 63 views
1

我似乎已经找到了如何做#1,但是,不知道该怎么办的第二部分...jQuery的检查,如果字符串开始,然后提取它

我有不同的p元素,每一系列的类:

<p class="note cxid-45 contextual-item">Example</p> 

我试图确定:

(1)类列表中包含一类具有“cxid-” (2)如果是这样,我会开始喜欢存储完整的类名

因此,在上面的标记,我想保存 “cxid-45” 在一个变量:C

我管理这个:

var pcl = $(this).attr("class").split(" "); 

if(pcl.indexOf('cxid-') >= 0) { 
    alert('found'); 
    //This works, but not sure how to get the full string into the variable 
    var c = ???; 
} else { 
    alert('not found'); 
    var c = ''; 
} 

回答

1

试试这个

var el=$('p[class*="cxid-"]'); 
var c=el.length ? el.prop('class').match(/cxid-[^\s]+/g)[0] : 'Not Found!'; 
alert(c); // If found then it'll alert the class name, otherwise 'Not Found!' 

DEMO.

1

您可以尝试这样的事:

var c = $(this).attr("class").match(/cxid-[^\s]+/g); 

c将类,其与启动array'cxid-'

if(c.length > 0){ 
    alert("There is at least on class,which starts with 'cxid-'"); 
}else{ 
    alert("Nothing found"); 
} 
相关问题