1

我似乎已经想出了如何做#1,但是,不知道如何做第二部分......

我有各种 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 = '';
}
4

2 回答 2

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!'

演示。

于 2012-07-12T17:34:50.730 回答
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");
}
于 2012-07-12T17:22:37.857 回答