jQuery 如何使用jQuery将id属性添加到具有特定类的html标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4299127/
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
How to add an id attribute to a html tag with a certain class using jQuery?
提问by Boris
I have a link with a class of special
and I want to add an id attribute to it.
我有一个类的链接,special
我想向它添加一个 id 属性。
Only one element in my document will have this class at any one time (I may remove and add a new one at some point).
在任何时候,我的文档中只有一个元素会有这个类(我可能会在某个时候删除并添加一个新元素)。
How would I add an id attribute to the element to change it from this:
我将如何向元素添加 id 属性以将其更改为:
<div class="special">
to this:
对此:
<div id="special-12345" class="special">
回答by prodigitalson
Adding the attribute is easy:
添加属性很简单:
$('.special').attr('id', 'your-id-value');
The more potentially problematic part will be ensuring that the id's you are adding are unique.
更有潜在问题的部分是确保您添加的 ID 是唯一的。
回答by rajangupta
Try this
尝试这个
$('div.special').attr('id','your-id');
回答by Steven
$(".special").attr("id","special-" + (new Date()).getTime());
回答by librewolf
Don't have the reputation to add a comment, but i believe it's benefitial enough for others searching for answer to state, that
没有添加评论的声誉,但我相信这对于其他人寻找答案的状态来说已经足够有益了,那就是
attr();
Doesn't simply addthe attribute but rather setsit. Important when there already is some set ID on the element.
不是简单地添加属性而是设置它。当元素上已经有一些设置 ID 时很重要。
回答by Andrea_dev
You can add id with:
您可以添加 id:
$('.special').attr('id', 'id-value');
Do you want change id?
你要换身吗?
$('.special').removeAttr('id').attr('id', 'id-value');