Javascript jQuery:只选择一个包含字符串的类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4106958/
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
jQuery: Select only a class containing a string?
提问by Shpigford
I'm currently using this to get the class for a specific bit of HTML on the page:
我目前正在使用它来获取页面上特定 HTML 位的类:
$(this).parent("div").attr('class')
But that div
has multiple classes: current_status status_billed
但这div
有多个类:current_status status_billed
My end goal here is to grab the class that starts with status_
and replace it with a different class name.
我的最终目标是获取以 开头的类status_
并将其替换为不同的类名。
So using my .parent()
function above, I'm able to select the div I need, but I then need to remove the status_billed
class and replace it with, for example, status_completed
(or a number of other class names).
因此,使用.parent()
上面的函数,我可以选择我需要的 div,但是我需要删除status_billed
该类并将其替换为例如status_completed
(或许多其他类名)。
回答by Matt Ball
Select div
s that have the status_billed
class:
选择div
具有以下status_billed
类别的s :
$(this).parent('div.status_billed')
Select div
s whose class
attribute contains status_
:
选择div
s 其class
属性包含status_
:
$(this).parent('div[class*=status_]')
That's about the best you'll get with jQuery selectors. You can do better using .filter()
:
这大概是您使用jQuery 选择器所能获得的最佳效果。您可以使用.filter()
以下方法做得更好:
$(this).parent('div').filter(function ()
{
var classes = $(this).attr('class').split(' ');
for (var i=0; i<classes.length; i++)
{
if (classes[i].slice(0,7) === 'status_')
{
return true;
}
}
return false;
});
...but I'm not sure why you're doing all this - .parent()
returns at most 1 element. Did you mean .closest()
or .parents()
?
...但我不确定你为什么要这样做 -.parent()
最多返回 1 个元素。你是说.closest()
还是.parents()
?