jQuery selectors with variables

2018-12-31 16:44发布

How to mix variables with selectors?

I have ID variable.

I want to select image with this id from div #one.

jQuery('#one img .id') is the selector. I've tried $('#one img .'+id) but doesn't work.

5条回答
看风景的人
2楼-- · 2018-12-31 17:11

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

DEMO

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

查看更多
流年柔荑漫光年
3楼-- · 2018-12-31 17:15

. is a class selector. Try changing that to a #:

$('#one img #'+id)
查看更多
余生无你
4楼-- · 2018-12-31 17:17

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);
查看更多
与风俱净
5楼-- · 2018-12-31 17:20

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

查看更多
回忆,回不去的记忆
6楼-- · 2018-12-31 17:27

This might just be a typo or you actually use the id variable in a class, but maybe it should be:

jQuery('#one img #'+id)
查看更多
登录 后发表回答