2013-07-30 16 views
1

我有很多元素:如何在jQuery和CSS中使用*获取类?

<span class="test"></span> 
<span class="aaa"></span> 
<span class="test-one"></span> 
<span class="test-two"></span> 
<span class="aaa-one"></span> 
<span class="test-two"></span> 

我怎样才能得到一个选择与名称测试*所有的跨度? 我可以:

$('.test, .test-one, .test-two') 

但也许是可能的正则表达式来得到这个?

$('.test*') 

在CSS

.test, .test-one, .test-two 

.test* 
+0

这就是为什么更具体的元素应该同时具有普通类和特定类的原因。在你的例子中,理想的解决方案是为所有测试跨度提供'test' – archil

回答

13

你滥用类,并正在寻找多类来代替:

<span class="test"></span> 
<span class="aaa"></span> 
<span class="test one"></span> 
<span class="test two"></span> 
<span class="aaa one"></span> 
<span class="test two"></span> 

现在,$('.one')将返回正确的第三和第五元素,$('.test')会返回除第二和第五之外的所有元素。

请注意,您也可以使用$('.two.test')来获得第4个和第6个元素。

+4

+1来给出正确答案,而不是他正在寻找的答案。 – Spudley

4

使用开始,与选择:

$('span[class^="test"]'). 

http://api.jquery.com/attribute-starts-with-selector/

+1

是的,这很好,直到他将另一个类添加到相同的元素。然后它会出错,他会很难找出原因。 – Spudley

+0

尽管它是当前问题的最佳解决方案,但请尽量避免帮助人们解决[XY问题]的更多问题(http://meta.stackexchange.com/questions/66377/what-is-the-xy这个问题)。 –

+0

@Spudley你说得对,尼尔斯的回答是更好的做法之一。了解这种可能性也很好,并且知道jQuery提供了多种选择器。 – DanFromGermany

0

我会改变类,因为HTML的标签可以同时有多个类:

<span class="test"></span> 
<span class="aaa"></span> 
<span class="test testone"></span> 
<span class="test testtwo"></span> 
<span class="aaa-one"></span> 
<span class="test testtwo"></span> 

如果您不能改变HTML,你可以使用javascript(jquery):

$('[class]').each(function(){ 
    var className = $(this).attr("class"); 
    if("test" == className.substring(0, 4)) //starts with "test" 
    { doSomething(); 
    } 
}); 

(此代码才能正常运行,如果标签有不超过一个班)

但是,这是肮脏的代码,因为它扫描具有类中的每个DOM元素。 如果您只想应用CSS样式,更好的解决办法,如果你不能改变的HTML,对所有可能的类添加到CSS-文件:

.test, .test-one, .test-two{ 
    ... 
} 

...或使用CSS3如其他答案中提到的选择器,但旧版浏览器不支持它。

+0

好吧,我的jQuery代码是废话,你不应该使用它。不知道jQuery有一个“开始 - ”选择器 – maja

0

您可以使用

$("span[class*='test']"); // element with test anywhere in class attribute 

$("span[class^='test']"); // element with test at the start in class attribute 

注意,如果该元素具有单班这些只会工作。

但是你最好用什么@Niels显示。

对于一个好的CSS选择参考:Tutorial from net.tutsplus.com

1

这不是来自小例子清楚是否有到-one-two类名的模式。

如果有一个模式,并且您的想法是交替类(例如奇数行和偶数行),那么您可能需要考虑使用nth-child()选择器。这将允许您选择相关元素,而不需要参考任何类名称。

在这种情况下,你可以做这样的事情:

<div class='container'> 
    <span class="test"></span> 
    <span class="test"></span> 
    <span class="aaa"></span> 
    <span class="test"></span> 
</div> 

,然后jQuery的:

$('container span:nth-child(odd)') 

$('container span:nth-child(even)') 

更多信息,请参见the jQuery manual for nth-child

如果这不是你要找的,那么我会建议遵循@NielsKeurentjes的建议,并在相关元素中使用多个类名。

希望有所帮助。

相关问题