jQuery:同时选择一个元素的类和 id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1944302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: select an element's class and id at the same time?
提问by ajsie
I've got some links that I want to select class and id at the same time.
我有一些链接,我想同时选择 class 和 id。
This is because I've got 2 different behaviours. When a class of links got one class name they behave in one way, when the same clas of links got another class name they behave differently. The class names are switch with jquery.
这是因为我有两种不同的行为。当一类链接获得一个类名时,它们的行为方式不同,当同一类链接获得另一个类名时,它们的行为方式不同。类名是用 jquery 切换的。
So I have to be able to select a links class AND id at the same time. Is this possible?
所以我必须能够同时选择一个链接类和 id。这可能吗?
I've tried:
我试过了:
$("a .save #country")
without any result.
没有任何结果。
回答by cletus
You can do:
你可以做:
$("#country.save")...
OR
或者
$("a#country.save")...
OR
或者
$("a.save#country")...
as you prefer.
根据你喜欢的。
So yes you can specify a selector that has to match ID andclass (and potentially tag name and anything else you want to throw in).
所以是的,您可以指定一个必须匹配 ID和类的选择器(以及可能的标签名称和您想要输入的任何其他内容)。
回答by Nikola
Just to add that the answer that Alex provided worked for me, and not the one that is highlighted as an answer.
只是补充一点,亚历克斯提供的答案对我有用,而不是突出显示为答案的答案。
This one didn't work for me
这个对我不起作用
$('#country.save')
But this one did:
但是这个做到了:
$('#country .save')
so my conclusion is to use the space. Now I don't know if it's to the new version of jQuery that I'm using (1.5.1), but anyway hope this helps to anyone with similar problem that I've had.
所以我的结论是使用空间。现在我不知道它是否适用于我正在使用的新版本的 jQuery (1.5.1),但无论如何希望这对我遇到过类似问题的人有所帮助。
edit:Full credit for explanation (in the comment to Alex's answer) goes to Felix Kling who says:
编辑:解释的全部功劳(在对亚历克斯回答的评论中)归功于 Felix Kling,他说:
The space is the descendant selector, i.e. A B means "Match all elements that
match B which are a descendant of elements matching A". AB means "select all
element that match A and B". So it really depends on what you want to achieve. #country.save
and #country .save
are not equivalent.
空格是后代选择器,即 AB 表示“匹配所有与 B 匹配的元素,这些元素是与 A 匹配的元素的后代”。AB 的意思是“选择所有匹配 A 和 B 的元素”。所以这真的取决于你想要达到的目标。#country.save
并且#country .save
不等价。
回答by Alex
It will work when adding space between id and class identifier
在 id 和类标识符之间添加空格时它会起作用
$("#countery .save")...
$("#countery .save")...
回答by Pekka
How about this code?
这段代码怎么样?
$("a.save#country")
回答by getack
In the end the same rules as for css apply.
最后,与 css 相同的规则适用。
So I think this referencecould be of some valuable use.
所以我认为这个参考可能会有一些有价值的用途。
回答by o.k.w
$("a.save, #country")
will select both "a.save" class and "country" id.
将同时选择“a.save”类和“国家/地区”ID。