问题描述
我正在做一个菜单,我需要从Jquery返回的元素列表中选择一个特定的元素.
I'm making a menu and i need to select one particular element from a list of element returned by Jquery.
当我在控制台上运行时:
When i run on console :
$("[type='subMenu']")
这将返回4个匹配的子菜单元素.
This returns 4 matching submenu elements.
<div type="subMenu" style="display:block">
<div type="subMenu" style="display:none">
<div type="subMenu" style="display:none">
现在,我只需要选择具有display:block
Now, i need to select only the element having display:block
我尝试了
$("[type='subMenu']").css('display') == 'block'
但这会提供false
作为输出.
和
$("[type='subMenu']").css('display')
这给出的输出为none
推荐答案
其他人已经指出了JQuery :visible
选择器.但是,如 JQuery API文档中指出的那样,它存在一些性能问题:
Others have already pointed out the JQuery :visible
selector. However, there are some performance issues with it, as pointed out in the JQuery API documentation:
- 因为
:visible
是jQuery扩展,而不是CSS规范的一部分,所以使用:visible
进行的查询无法利用本机DOMquerySelectorAll()
方法提供的性能提升.为了在使用:visible
选择元素时获得最佳性能,请首先使用纯CSS选择器选择元素,然后使用.filter(":visible")
. - 大量使用此选择器可能会对性能产生影响,因为它可能会迫使浏览器在确定可见性之前重新渲染页面.通过其他方法(例如,使用类)跟踪元素的可见性可以提供更好的性能.
- Because
:visible
is a jQuery extension and not part of the CSS specification, queries using:visible
cannot take advantage of the performance boost provided by the native DOMquerySelectorAll()
method. To achieve the best performance when using:visible
to select elements, first select the elements using a pure CSS selector, then use.filter(":visible")
. - Using this selector heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility. Tracking the visibility of elements via other methods, using a class for example, can provide better performance.
如果您希望避免这些问题,则可以使用本机CSS选择器.在普通的JavaScript中,这将为您解决问题:
If you'd prefer to avoid those issues, you could use a native CSS selector, instead. In plain ol' normal JavaScript, this would do the trick for you:
document.querySelector("[type=subMenu][style*=display\\:block]");
或者,如果您需要一次选择多个元素:
Or, if you need to select multiple elements at once:
document.querySelectorAll("[type=subMenu][style*=display\\:block]");
我相信两者在JQuery中的等效项(我不使用它)将是:
I believe the equivalent in JQuery (I don't use it) for both would be:
$("[type=subMenu][style*=display\\:block]");
如果要在这些标签上内联设置的唯一样式是display
,则可以从style
属性选择器中省略*
.
If the only style that will ever be set inline on those tags is display
then you can omit the *
from the style
attribute selector.
这篇关于从项目列表中仅选择(display:block)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!