jQuery从变量中选择类 [英] Jquery select class from variable

查看:79
本文介绍了jQuery从变量中选择类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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从变量中选择类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆