如何在相同的 CLASS 名称上添加不同的 ID?

How to add different ID on same CLASS name?

我想完成的事情。我在网站上有一个清单,我想在单击按钮时再添加一个(类似于 trello 卡)。因为它有很多 html,所以我想从外部 html 文件中添加它。但我希望每次添加时都有不同的 ID。每个 id 应该看起来像 id 名称和编号。

希望清楚。

代码如下:

$('.new-checklist').on('click', function(e){
  e.preventDefault();
  $.get('new-chk.html',function(data) {
    $('.checklist').append(data);
    $('.checklist-all').attr("id", "chk");
  });
  return false;
}); 

对于您正在尝试做的事情,您应该按位置尝试不同的 selector like,而不是 CLASS,因为这会 select [=] 的所有元素27=] 而不仅仅是你想要的那个。 由于您使用 .append 添加新支票,因此您知道这是最后一个支票,因此您可以:

$('.checklist').children().last().attr("id", "chk");

您的代码应该是:

    $('.new-checklist').on('click', function(e){
      e.preventDefault();
      $.get('new-chk.html',function(data) {
        $('.checklist').append(data);
        $('.checklist').children().last().attr("id", "{NEW_ID}");
      });
      return false;
    });

此外,您可以将 html 放在外部文件中,但您应该只加载一次,而不是每次要添加新检查时都执行请求。

可以使用attr()方法可用的匿名函数修改属性:

$('.checklist-all').attr("id", function(i){
  // 'i' : the index of the current element of
  // of the collection over which the method
  // iterates:

  // here we return the string 'chk' concatenated
  // with the index:
  return 'chk' + i;
});

虽然要设置 id 我个人更喜欢使用 prop(),但在实践中并没有真正的区别。尽管如此,我还是回应了 这个问题:

Why do the checkboxes need IDs in the first place?

参考文献: