带有变量的 jQuery 选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4893436/
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 selectors with variables
提问by anonymous
How to mix variables with selectors?
如何将变量与选择器混合?
I have ID variable.
我有 ID 变量。
I want to select image with this id from div #one.
我想从 div #one 中选择具有此 ID 的图像。
jQuery('#one img .id')
is the selector. I've tried $('#one img .'+id)
but doesn't work.
jQuery('#one img .id')
是选择器。我试过了,$('#one img .'+id)
但不起作用。
回答by Ben Rowe
Edit: Based on your comment below, you would use this:
编辑:根据您在下面的评论,您将使用此:
$('#one img.'+id)
In your question you have a space between img
and the .class
, I've simply removed that so you get img.className
or img.'+className
在您的问题中,您在img
和之间有一个空格.class
,我只是将其删除,因此您得到img.className
或img.'+className
With the introduction of template literalsin ECMAScript 2015, you can also do
随着ECMAScript 2015中模板文字的引入,您还可以
$(`#one img.${id}`)
回答by Alan Christopher Thomas
This might just be a typo or you actually use the id
variable in a class, but maybe it should be:
这可能只是一个错字,或者您实际上id
在类中使用了该变量,但它可能应该是:
jQuery('#one img #'+id)
回答by Chris Laplante
.
is a class selector. Try changing that to a #
:
.
是一个类选择器。尝试将其更改为 a #
:
$('#one img #'+id)
回答by user3094826
ID's should be unique in your HTML. So you should be able to select the ID directly without worrying about which DIV it is in. Since you mention the ID is attached to the img
tag, then this should be enough.
ID 在您的 HTML 中应该是唯一的。所以你应该可以直接选择ID,而不必担心它在哪个DIV中。既然你提到ID是附加到img
标签上的,那么这应该就足够了。
$('#' + id);