ID 数组 - 如何使用 JavaScript / JQuery 进行选择?

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

Array of IDs - how to select with JavaScript / JQuery?

jquerycss-selectors

提问by James L

I have an array of element identifiers, coming back from some server-side validation. The IDs aren't prefixed with a '#'. Rather than going through the array and prefixing a # to each member, is there jquery means of directly selecting all elements by their IDs?

我有一组元素标识符,从一些服务器端验证回来。ID 不以“#”为前缀。不是遍历数组并为每个成员添加 # 前缀,而是有 jquery 方法通过它们的 ID 直接选择所有元素吗?

采纳答案by Maine

Don't you forget "old fashioned" getElementById - it doesn't require hashing the ids. Then just feed nodes to jQuery to get a jQuery object:

不要忘记“老式” getElementById - 它不需要对 id 进行哈希处理。然后只需将节点提供给 jQuery 即可获得一个 jQuery 对象:

var ids = ['jq-primarySearch', 'jq-n-CSS'];
var nodes = $.map( ids, function(i) { return document.getElementById(i) } );
var jqObj = $(nodes);

回答by Greg

You could just join them, like this:

你可以加入他们,像这样:

var ids = ['div1', 'div2', 'div3'];

$('#' + ids.join(',#')).click(function() { alert('hi'); });

回答by stusmith

(NB - I haven't tried this - this is off the top of my head)

(注意 - 我还没有尝试过 - 这超出了我的脑海)

Let's say your array is "arr".

假设您的数组是“arr”。

Couldn't you map your array of string identifiers into an array of jQuery objects, then concantenate them all using the usual jQuery selector?

您不能将字符串标识符数组映射到 jQuery 对象数组,然后使用通常的 jQuery 选择器将它们全部连接起来吗?

$($.map(arr, function(id) { return $('#' + id); }))

回答by Elzo Valugi

In jQuery you can select by ID like this

在 jQuery 中,您可以像这样按 ID 选择

$("[id=id_value]"); // returns 1 id

if you name them something like id_1 and id_2 you can do this

如果您将它们命名为 id_1 和 id_2 之类的东西,您可以这样做

$("[id^='id_]") // returns multiple 

回答by bobince

Just do the node selection yourself then wrap the result:

只需自己进行节点选择,然后包装结果:

$(document.getElementById(id))

saves constructing a string selector that jQuery will only have to parse back in and then do exactly the same thing. Plus you don't have to worry about escaping characters like ‘:' and ‘.' which are valid in IDs but mean something else in selectors.

保存构造一个字符串选择器,jQuery 只需要解析它,然后做完全相同的事情。另外,您不必担心转义字符,如 ':' 和 '.' 在 ID 中是有效的,但在选择器中意味着其他的东西。

回答by peirix

If you have the ID as a string you can select it in jQuery like this

如果您将 ID 作为字符串,则可以像这样在 jQuery 中选择它

$("#"+id); //gives you one element

If you have multiple ID's that are similar, then use Elzo's suggestion.

如果您有多个相似的 ID,请使用 Elzo 的建议。