带有变量的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:08:20  来源:igfitidea点击:

jQuery selectors with variables

jqueryvariablesjquery-selectors

提问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 imgand the .class, I've simply removed that so you get img.classNameor img.'+className

在您的问题中,您在img和之间有一个空格.class,我只是将其删除,因此您得到img.classNameimg.'+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 idvariable 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 imgtag, then this should be enough.

ID 在您的 HTML 中应该是唯一的。所以你应该可以直接选择ID,而不必担心它在哪个DIV中。既然你提到ID是附加到img标签上的,那么这应该就足够了。

$('#' + id);

回答by Joko Wandiro

Maybe you want to select img which set with specific class and save this class into id variable within div element with id='one'.

也许您想选择设置了特定类的 img 并将此类保存到 id='one' 的 div 元素中的 id 变量中。

DEMO

演示

In demo i select img element, clone it, and append to div id=one.

在演示中,我选择 img 元素,克隆它,并附加到 div id=one。