jQuery 选择器:异或
我使用一组 jQuery 选择器在多个不同的页面上插入一些内容;然而,有些页面具有多个选择器,因此内容会在页面上插入多次。例如:
$('div.rColInnerL:first, div.box300.bdr.search:first, h2.blt13:first').before('<div>Hello World!</div>');
是否可以在 jQuery 选择器中使用一种异或,表示只应使用其中一个?非常感谢。
I'm using a set of jQuery selectors to insert some content on a number of different pages; however some pages feature more than one of the selectors, so the content is inserted more than once on the page. For example:
$('div.rColInnerL:first, div.box300.bdr.search:first, h2.blt13:first').before('<div>Hello World!</div>');
Is it possible to use a kind of exclusive-OR in the jQuery selector, to say that only one of these should be used? Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将找到的元素集减少到第一个:
You can reduce the set of found elements to the first one:
从表面上看,您似乎可以使用
first()
(docs) 方法来获取第一个匹配项。当然,这取决于第一个始终是正确的。由于选择器匹配的元素的使用似乎可能存在一些变化,因此这可能是一个问题。
jQuery 不一定按照选择器的顺序返回元素,而是按照它们在页面上出现的顺序返回元素,因此这不一定复制您正在寻找的“异或”行为。
更准确地说,您需要更明确的内容:
这是 jQuery 不按选择器顺序返回元素的示例:
即使
#second
位于选择器中的第一个,第一个匹配项是显示为#first
元素,因为它在文档中排在第一位。示例: http://jsfiddle.net/XxXXc/
On the surface it would seem like you could use the
first()
(docs) method to get the first match.Of course this will depend on the first one always being the correct one. Since it seems like there may be some variation in the use of the element that is matched by the selector, it may be an issue.
jQuery does not necessarily return the elements in the order of the selector, but rather in the order of their appearance on the page, so this doesn't necessarily replicate an "exclusive OR" behavior that you're looking for.
To be more precise, you'd need something more explicit:
Here's an example of jQuery not returning the elements in the order of the selector:
Even though
#second
is first in the selector, the first match is shown as the#first
element, because it comes first in the document.Example: http://jsfiddle.net/XxXXc/
所选答案对我不起作用。
我用过这个:
The selected answer doesn't work to me.
I used this: