表单: WebNotes
用户: dreamable
创建日期: 2021-01-19 12:35:01 UTC
更新日期: 2021-01-19 12:35:01 UTC
引用:(Table ID 25, Record ID 1)

标题 :
How to update all IDs by Javascript
笔记 :

guide

var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
   var target = $(this);
   var id = target.attr("id"); // Get the ID
   target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());

I use it for add an similar item for array in ShujuQiu project. However, when it's cloned, all ID the same with the original one. I need to update all IDs to make them unique. Otherwise, Javascript will be confused.

  $('form').on('click', '.add_record_array_element', function(event) {
    console.log("DEBUG:: add record array element!")
    // Find the first parent with class "record_array_element"
    item = $(this).parents('.record_array_element').first()
    // Record cell
    cell = item.parent();
    // Clone
    new_item = item.clone()
    // Add prefix to all IDs to make them uniq. https://stackoverflow.com/questions/16465694
    var time = new Date().getTime();
    new_item.find("[id]").each(function() { // Select all elements with an ID
       var target = $(this);
       var id = target.attr("id");         // Get the ID
       target.attr("id", time+"_"+id);     // Set the id
    });
    // Append
    cell.append(new_item)
    return event.preventDefault();
  });
标签: