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
addID in jQuery?
提问by eozzy
Is there any method available to add IDs like there is for adding a class - addClass()?
是否有任何方法可用于添加 ID,就像添加类一样 - addClass()?
回答by CMS
回答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');
- get actual ID
- put actuel ID and add the new one
- 获取实际ID
- 输入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。希望这可以帮助!