jQuery - 添加 ID 而不是类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2176986/
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
jQuery - Add ID instead of Class
提问by CLiown
I'm using the current jQuery:
我正在使用当前的jQuery:
$(function() {
$('span .breadcrumb').each(function(){
$('#nav').addClass($(this).text());
$('#container').addClass($(this).text());
$('.stretch_footer').addClass($(this).text())
$('#footer').addClass($(this).text());
});
});
It applies the text held in the breadcrumb to 4 elements on the page, allowing me to style specifically to the page there on.
它将面包屑中的文本应用到页面上的 4 个元素,让我可以专门针对那里的页面设置样式。
I'd like to try adding an ID instead of a class, how can I achieve this?
我想尝试添加一个 ID 而不是一个类,我该如何实现?
回答by Sarfraz
Try this:
尝试这个:
$('element').attr('id', 'value');
So it becomes;
所以它变成了;
$(function() {
$('span .breadcrumb').each(function(){
$('#nav').attr('id', $(this).text());
$('#container').attr('id', $(this).text());
$('.stretch_footer').attr('id', $(this).text())
$('#footer').attr('id', $(this).text());
});
});
So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...
因此,您正在更改/覆盖三个元素的 id 并向一个元素添加一个 id。可以根据需要修改...
回答by Anthony
Keep in mind this overwrites any ID that the element already has:
请记住,这会覆盖元素已有的任何 ID:
$(".element").attr("id","SomeID");
The reason why addClass
exists is because an element can have multiple classes, so you wouldn't want to necessarily overwrite the classes already set. But with most attributes, there is only one value allowed at any given time.
addClass
存在的原因是因为一个元素可以有多个类,因此您不必覆盖已经设置的类。但是对于大多数属性,在任何给定时间都只允许一个值。
回答by meouw
$('selector').attr( 'id', 'yourId' );
回答by geekbuntu
if you want to 'add to the id' rather than replace it
如果您想“添加到 ID”而不是替换它
capture the current id first, then append your new id. especially useful for twitter bootstrap which uses input states on their forms.
首先捕获当前 id,然后附加您的新 id。对于在表单上使用输入状态的 twitter bootstrap 尤其有用。
new_id = '{{old_id}} inputSuccess';
old_id = that.attr('id');
that.attr('id', new_id.replace( /{{old_id}}/ig,old_id));
if you do not - you will lose any properties you previous set.
如果不这样做 - 您将丢失之前设置的任何属性。
hth,
嗯,
回答by Nicolai
Im doing this in coffeescript
我在咖啡脚本中这样做
booking_module_time_clock_convert_id = () ->
if $('.booking_module_time_clock').length
idnumber = 1
for a in $('.booking_module_time_clock')
elementID = $(a).attr("id")
$(a).attr( 'id', "#{elementID}_#{idnumber}" )
idnumber++