jQuery-添加ID而不是类


94

我正在使用当前的jQuery

$(function() {
    $('span .breadcrumb').each(function(){
        $('#nav').addClass($(this).text());
        $('#container').addClass($(this).text());
        $('.stretch_footer').addClass($(this).text())
        $('#footer').addClass($(this).text());
    });
});

它将面包屑中包含的文本应用于页面上的4个元素,使我可以为其上的页面专门设置样式。

我想尝试添加一个ID而不是一个类,如何实现呢?


ID必须是唯一的,才是有效的XHTML。ID必须符合更严格的规则,例如,不能有空格,以字母或_开头,只能包含字母,数字或有限数量的其他字符。
Doug Domeny'2

7
@Peter:向Wikipedia添加链接似乎有点多余。
尼克


Answers:


223

试试这个:

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

变成了;

$(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());
    });
});

因此,您要更改/覆盖三个元素的ID,并将一个ID添加到一个元素。您可以根据需要进行修改...


1
缓存如何?而不是制作“ this”的4个不同的jQuery对象。var text = $(this).text();
PetersenDidIt'2

@petersendidt:同意,我在回答中说,他需要根据需要进行修改。
Sarfraz

甚至更好:$('#nav, #container, .stretch_footer, #footer').attr('id', $(this).text());..不是在这里使用ID是个好主意。
尼克

这只会工作一次,之后ID会发生变化……此外,您将继续覆盖相同的ID,因此您最好为$('#nav, #container, .stretch_footer, #footer').attr('id', $('span .breadcrumb:first').text())(或lastfor .stretch_footer)执行此操作。无论如何,这很奇怪。
科比

26

请记住,这会覆盖该元素已具有的所有ID:

 $(".element").attr("id","SomeID");

之所以addClass存在,是因为一个元素可以具有多个类,所以您不必覆盖已设置的类。但是对于大多数属性,在任何给定时间仅允许一个值。



3

如果您想“添加到ID”而不是替换它

首先捕获当前ID,然后附加新ID。对于在表单上使用输入状态的twitter引导程序特别有用。

    new_id = '{{old_id}} inputSuccess';
    old_id = that.attr('id');
    that.attr('id', new_id.replace( /{{old_id}}/ig,old_id));

如果您不这样做,则将丢失先前设置的所有属性。

hth,


有效元素只能有一个ID。stackoverflow.com/questions/192048/...
colonelclick

3

我在咖啡脚本中这样做

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++
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.