Jquery 从变量中选择类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3951302/
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 class from variable
提问by Mr Hyde
I am using Jquery to find a class by variable. So,
我正在使用 Jquery 按变量查找类。所以,
var className = "whatever";
$("#container ul li") if contains element with className, do this
$("#container ul li") 如果包含具有 className 的元素,请执行此操作
How do I write the above code?
上面的代码怎么写?
Is it
是吗
$("#container ul li").find("."+ className).each(function(){
console.log("I found one");
});
Obviously the code doesn't work
显然代码不起作用
回答by user113716
Is the className
on the <li>
element? If so, you could do this:
是className
在<li>
元素上吗?如果是这样,你可以这样做:
$('#container ul li.' + className)...
You're just concatenating the className into the selector string (with the class selector).
您只是将 className 连接到选择器字符串中(使用类选择器)。
Or this will give you the same result.
或者这会给你同样的结果。
$('#container ul li').filter('.' + className)...
Which is the similar to your .find()
solution, but uses .filter()
to limit the <li>
elements found to those with the className
.
这与您的.find()
解决方案相似,但用于.filter()
将<li>
找到的元素限制为带有className
.
If the element with the className
is a descendant of the <li>
element, then using .find()
should work, or you could do:
如果带有 的元素className
是该元素的后代<li>
,则using.find()
应该可以工作,或者您可以执行以下操作:
$('#container ul li .' + className)...
...which almost looks the same as the one above, but introduces a space after li
, which is a descendant selector.
...看起来与上面的几乎相同,但在 之后引入了一个空格li
,这是一个后代选择器。