简体   繁体   中英

How to add different ID on same CLASS name?

What I would like to accomplish. I have a checklist in a website, and I want to add one more on button click (similar like in trello card). Because it is a lot of htlm I would like to add it from external html file. But I want different ID with each addition. Every id should look like id name and number.

Hope it is clear.

Here is the code:

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

For what you are trying to do you should try a different selector like by position, rather than CLASS, since this would select all the elements of that class and not just the one you want. Since you use .append to add the new check, then you know it is the last one so you can do:

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

Your code should be:

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

Also you it's ok to have the html in an external file but you should load it just once, instead of doing a request each time you want to add a new check.

You can use the anonymous function available to the attr() method to modify the attribute:

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

Although to set the id I'd personally prefer to use prop() , but there's no real difference in practice. That said, though, I'd echo Barmar's comment to the question:

Why do the checkboxes need IDs in the first place?

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM