jQuery 当类名以某个单词开头时选择一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6055355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select an element when the class name starts with a certain word
提问by Charles Yeung
Suppose I have the elements as below:
假设我有以下元素:
<div class="home">
<div class="tab231891230"></div>
<div class="tab121232441"></div>
<div class="tab123134545"></div>
</div>
How can I use jQuery to select the div element that the class starts with "tab"
?
如何使用 jQuery 选择类开头的 div 元素"tab"
?
回答by kapa
It is called the Attribute Starts With Selector. My example sets a red text color on the elements:
它被称为Attribute Starts With Selector。我的示例在元素上设置了红色文本颜色:
$('[class^="tab"]').css('color', 'red');
Please note that if the elements have more than one class and the other precedes the one with tab
inside (class="nyedva tab231891230"
) the element won't be selected by this selector.
请注意,如果元素有多个类,而另一个类位于带有tab
inside ( class="nyedva tab231891230"
) 的类之前,则此选择器将不会选择该元素。
If you want to select even these, you can use this example:
如果你甚至想选择这些,你可以使用这个例子:
$('.home div').filter(function () {
return this.className.match(/\btab/);
}).css('color', 'red');
回答by cyberfly
If you have multiple class inside one element, use this to select
如果您在一个元素中有多个类,请使用它来选择
$("[class*='tab']");
It will work with element like this
它将与这样的元素一起使用
<div class="home">
<div class="module tab231891230"></div>
<div class="module tab121232441"></div>
<div class="module tab123134545"></div>
Reference : jquery attribute-contains selector
回答by Tim
You can do it like this:
你可以这样做:
$('div[class^="tab"]');
回答by metaforce
why use that? that number, you can assign to rel or id attribute, like this:
为什么要使用它?该数字,您可以分配给 rel 或 id 属性,如下所示:
<div class="home">
<div class="tab" rel="231891230"></div>
<div class="tab" rel="121232441"></div>
<div class="tab" rel="123134545"></div>
</div>
then it will be accessible at:
然后它可以在以下位置访问:
$('div.tab').click(yourhandler);
or even, add a subclass of that current "tab" class:
甚至,添加当前“选项卡”类的子类:
<div class="home">
<div class="tab 231891230"></div>
<div class="tab 121232441"></div>
<div class="tab 123134545"></div>
</div>
then, just select by "tab" class like in the jQuery example above, and do whatever you want with the second class (check if it's there, remove it).
然后,只需像上面的 jQuery 示例一样通过“tab”类进行选择,然后对第二个类执行您想要的任何操作(检查它是否存在,将其删除)。
check these:
检查这些:
http://api.jquery.com/class-selector/
http://api.jquery.com/class-selector/
http://api.jquery.com/hasClass/
http://api.jquery.com/hasClass/
http://api.jquery.com/addClass/
http://api.jquery.com/addClass/