问题描述
我正在使用Jquery通过变量查找类.所以,
I am using Jquery to find a class by variable. So,
var className = "whatever";
$(#container ul li")如果包含具有className的元素,请执行此操作
我如何编写以上代码?
是
$("#container ul li").find("."+ className).each(function(){
console.log("I found one");
});
很明显,该代码无法正常工作
Obviously the code doesn't work
推荐答案
<li>
元素上的className
是吗?如果是这样,您可以这样做:
Is the className
on the <li>
element? If so, you could do this:
$('#container ul li.' + className)...
您只是将className连接到选择器字符串中(使用类选择器).
You're just concatenating the className into the selector string (with the class selector).
否则这将给您相同的结果.
Or this will give you the same result.
$('#container ul li').filter('.' + className)...
与您的.find()
解决方案类似,但是使用.filter()
来限制对于使用className
的人发现了<li>
个元素.
Which is the similar to your .find()
solution, but uses .filter()
to limit the <li>
elements found to those with the className
.
如果带有className
的元素是<li>
元素的后代,则使用.find()
应该可以,或者您可以这样做:
If the element with the className
is a descendant of the <li>
element, then using .find()
should work, or you could do:
$('#container ul li .' + className)...
...看起来几乎与上面的相同,但是在li
之后引入了一个空格,即后代选择器.
...which almost looks the same as the one above, but introduces a space after li
, which is a descendant selector.
这篇关于jQuery从变量中选择类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!