我想知道是否有一种方法在jQuery选择器中有“或”逻辑。例如,我知道一个元素是类为classA或类为classB的元素的后代,我想做一些类似于element .parents(`。classA或。classb ')。jQuery是否提供这样的功能?
当前回答
我写了一个非常简单(5行代码)的插件来实现这个功能:
http://byrichardpowell.github.com/jquery-or/
它允许你有效地说“获取这个元素,或者如果那个元素不存在,使用这个元素”。例如:
$( '#doesntExist' ).or( '#exists' );
虽然接受的答案提供了类似的功能,如果两个选择器(逗号之前和之后)都存在,两个选择器都将返回。
我希望这对任何可能通过谷歌登陆这个页面的人都有帮助。
其他回答
如果你想使用element = element1 || element2的标准构造,其中JavaScript将返回第一个为真值的元素,你可以这样做:
element = $('#someParentElement .somethingToBeFound') || $('#someParentElement .somethingElseToBeFound');
它将返回实际找到的第一个元素。但更好的方法可能是使用jQuery的选择器逗号结构(它返回一个找到的元素数组),以这种方式:
element = $('#someParentElement').find('.somethingToBeFound, .somethingElseToBeFound')[0];
它将返回第一个找到的元素。
我不时地使用它来查找列表中的活动元素,或者在没有活动元素的情况下查找某个默认元素。例如:
element = $('ul#someList').find('li.active, li:first')[0]
它将返回带有active类的任何li,如果没有,则只返回最后一个li。
Either will work. There are potential performance penalties, though, as the || will stop processing as soon as it finds something truthy whereas the array approach will try to find all elements even if it has found one already. Then again, using the || construct could potentially have performance issues if it has to go through several selectors before finding the one it will return, because it has to call the main jQuery object for each one (I really don't know if this is a performance hit or not, it just seems logical that it could be). In general, though, I use the array approach when the selector is a rather long string.
最后我找到了如何做到这一点:
div:not(:not(.classA,.classB)) > span
(选择具有类classA或具有直接子跨度的类b的div)
如果有多个jQuery对象需要连接,使用逗号可能是不够的。
.add()方法将所选元素添加到结果集中:
// classA OR classB
jQuery('.classA').add('.classB');
它比'更啰嗦。classA, .classB',但允许你构建更复杂的选择器,如下所示:
// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));
使用逗号。
'.classA, .classB'
你可以选择省略空格。
我写了一个非常简单(5行代码)的插件来实现这个功能:
http://byrichardpowell.github.com/jquery-or/
它允许你有效地说“获取这个元素,或者如果那个元素不存在,使用这个元素”。例如:
$( '#doesntExist' ).or( '#exists' );
虽然接受的答案提供了类似的功能,如果两个选择器(逗号之前和之后)都存在,两个选择器都将返回。
我希望这对任何可能通过谷歌登陆这个页面的人都有帮助。
推荐文章
- 在数组中获取所有选中的复选框
- JSHint和jQuery: '$'没有定义
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- 如何用JavaScript截屏一个div ?
- 如何检测“搜索”HTML5输入的清除?
- 当元素从DOM中移除时触发事件
- Ajax成功事件不工作
- 引导下拉与Hover
- jQuery的.bind() vs. on()
- jQuery .live() vs .on()方法,用于在加载动态html后添加单击事件
- 事件。returnValue已弃用。请使用标准的event.preventDefault()
- 如何处理模式关闭事件在Twitter引导?
- 防止浏览器加载拖放文件
- 清除输入文本内的图标