javascript 如何通过 id 使用 JQuery 动态选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6369375/
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-10-25 20:25:31  来源:igfitidea点击:

How to dynamic select element with JQuery by id

javascriptjquery

提问by Drkosh

I need to dynamic select element with JQuery, I get in code id of element. How to do that ? I've tried:

我需要用 JQuery 动态选择元素,我得到了元素的代码 ID。怎么做 ?我试过了:

var sel='\'#'+id+'\'';
var elem+$(sel);

but it doesn't work ( id is string id of element).

但它不起作用( id 是元素的字符串 id )。

回答by Tom Walters

You would use code such as

您将使用诸如

var ID = 'whatEver';
$('#' + ID).action();

You would then be able to use that to select whatever element you are after.

然后您就可以使用它来选择您想要的任何元素。

回答by Luke Dennis

You don't need the extra quotes. Just:

您不需要额外的引号。只是:

var elem = $("#"+id);

回答by anandharshan

A live example:: to find text area with attribute data-comment-id with any value

一个活生生的例子:: 查找具有任何值的属性 data-comment-id 的文本区域

var value = "anyValue";
$('textarea[data-comment-id='+value+']')