2012-07-12 32 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"); 
} 
相關問題