jQuery jQuery中的addID?

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

addID in jQuery?

jqueryjquery-selectors

提问by eozzy

Is there any method available to add IDs like there is for adding a class - addClass()?

是否有任何方法可用于添加 ID,就像添加类一样 - addClass()?

回答by CMS

ID is an attribute, you can set it with the attrfunction:

ID 是一个属性,你可以用attr函数设置它:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDssince an element can only have one identifier and this identifier must be unique.

我不确定添加 ID是什么意思,因为一个元素只能有一个标识符,而且这个标识符必须是唯一的。

回答by scunliffe

do you mean a method?

你是说方法吗?

$('div.foo').attr('id', 'foo123');

Just be careful that you don't set multiple elements to the same ID.

请注意不要将多个元素设置为相同的 ID。

回答by Sylvain

Like this :

像这样 :

var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
  1. get actual ID
  2. put actuel ID and add the new one
  1. 获取实际ID
  2. 输入actuel ID并添加新的

回答by Danny Dickson

I've used something like this before which addresses @scunliffes concern. It finds all instances of items with a class of (in this case .button), and assigns an ID and appends its index to the id name:

我之前使用过类似的东西来解决@scunliffes 的问题。它查找类为(在本例中为 .button)的所有项目实例,并分配一个 ID 并将其索引附加到 id 名称:

$(".button").attr('id', function (index) {
 return "button-" + index;
});

So let's say you have 3 items with the class name of .button on a page. The result would be adding a unique ID to all of them (in addition to their class of "button").

因此,假设您在页面上有 3 个类名为 .button 的项目。结果将是为所有这些添加一个唯一的 ID(除了它们的“按钮”类)。

In this case, #button-0, #button-1, #button-2, respectively. This can come in very handy. Simply replace ".button" in the first line with whatever class you want to target, and replace "button" in the return statement with whatever you'd like your unique ID to be. Hope this helps!

在这种情况下,分别是#button-0、#button-1、#button-2。这可以派上用场。只需将第一行中的“.button”替换为您想要定位的任何类,然后将返回语句中的“button”替换为您希望的唯一 ID。希望这可以帮助!