检查选择器是否与特定类标记的元素相匹配 [英] Checking if a selector matches elements marked by a specific class

查看:152
本文介绍了检查选择器是否与特定类标记的元素相匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的jQuery选择器(一个字符串):

I have a generic jQuery selector (a string):

var selector = '#files li div';

和课程名称:

var myClass = 'folder';

我想检查选择器是否匹配具有类的元素存储到 myClass
到目前为止,我使用一个选择器的实例来调用hasClass()方法:

I want to check if the selector matches elements having the class stored into myClass. As far as now I used an instance of the selector to invoke the method hasClass():

var match = $(selector).hasClass(myClass);

它的工作原理,但我认为它可能会存在一些更有效的jQuery方法,它允许不创建一个jQuery实现以获取所有与选择器匹配的元素。

我担心的是仅由此检查创建的实例使用的内存,而不是在伪类的方法内部不能返回/公开任何对这个实例的引用。

It works, but I thought it may exist some more efficient jQuery method which allows not to create a jQuery instance to get all the elements matched by the selector.
My worry is the memory used by the instance created only for this check and nothing more, althought it is inside the method of a pseudo-class which does not return/expose any reference to this instance.

你能否提出更好的建议?

Can you suggest something better?

;编辑>

在示例中,我将 myClass 的值设置为文件夹,只是为了方便地表示问题,但在应用程序中,我不知道它,因为它是由用户操作定义的。

< / EDIT>

<EDIT>
In the example showed I set the value of myClass to "folder" just to easily represent the problem, but in the app I do not know it in advance, since it is defined by user actions.
</EDIT>

推荐答案

hasClass()将返回true,如果匹配元素的任何具有指定的类;

hasClass() will return true if any of the matched elements has the specified class; not if all of them do.

您可能会发现以下更多的是您想要的:

You might find the following is more what you want:

var match = $(selector).filter('.' + myClass);

但是您可以简化为:

var match = $(selector + '.' + myClass);

然后,您可以使用检查是否留下任何元素。长度属性。

And you'd then check whether you have any elements left using the .length attribute.

if (match.length) // then some were matched!

在担心内存使用方面... 不要 即可。 过早优化是所有邪恶的根源。这里的内存使用情况是 。如果要优化您的程序(目前是否有需要),请查看被称为大量次的函数,或查看具有大量迭代的循环,或查看DOM操作,并查看是否它们可以组合;一个jQuery选择器不会使您的程序的相对速度与任何的差异。

In terms of worrying about memory usage... don't. premature optimization is the root of all evil. The memory usage here is tiny. If you want to optimize your program (is there a need at the moment?), look at functions which are called a large number of times, or look within loops that have a large number of iterations, or look at DOM manipulation and see if they can be combined; one jQuery selector isn't going to make any difference to your program's speed in relative terms.

这篇关于检查选择器是否与特定类标记的元素相匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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