如何使用 ID 变量在 jQuery 中选择元素?

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

How do I select an element in jQuery by using a variable for the ID?

jquerysyntaxselect

提问by Tony

For example, the following selects a division with id="2":

例如,下面选择一个 id="2" 的分区:

row = $("body").find("#2");

How do I do something like this:

我该如何做这样的事情:

row_id = 5;
row = $("body").find(row_id);

The above syntax produces an error. I checked the jQuery documentation and answers here without success.

上述语法产生错误。我在这里检查了 jQuery 文档和答案,但没有成功。

回答by Rick Hochstetler

row = $("body").find('#' + row_id);

More importantly doing the additional body.find has no impact on performance. The proper way to do this is simply:

更重要的是,执行额外的 body.find 对性能没有影响。正确的方法很简单:

row = $('#' + row_id);

回答by John Rasch

The shortest way would be:

最短的方法是:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

将搜索限制在身体上没有任何好处。

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

此外,您应该考虑将您的ids重命名为更有意义的名称(并且根据 Paolo 的回答符合 HTML 标准),尤其是当您还有另一组数据需要命名时。

回答by Paolo Bergantino

Doing $('body').find();is not necessary when looking up by ID; there is no performance gain.

$('body').find();通过ID查找时不需要做;没有性能提升。

Please also note that having an ID that starts with a number is not valid HTML:

另请注意,以数字开头的 ID不是有效的 HTML

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_") 、冒号 (":") 和句点 (".")。

回答by Amr Elgarhy

You can do it like this:

你可以这样做:

row_id = 5;
row = $("body").find('#'+row_id);

回答by Bert Lamb

There are two problems with your code

你的代码有两个问题

  1. To find an element by ID you must prefix it with a "#"
  2. You are attempting to pass a Number to the find function when a String is required (passing "#" + 5 would fix this as it would convert the 5 to a "5" first)
  1. 要通过 ID 查找元素,您必须在它前面加上“#”
  2. 您正在尝试在需要字符串时将数字传递给 find 函数(传递“#”+ 5 将解决此问题,因为它会首先将 5 转换为“5”)

回答by Zifre

I don't know much about jQuery, but try this:

我不太了解 jQuery,但试试这个:

row_id = "#5";
row = $("body").find(row_id);

Edit: Of course, if the variable is a number, you have to add "#"to the front:

编辑:当然,如果变量是数字,则必须"#"在前面添加:

row_id = 5
row = $("body").find("#"+row_id);