使用新ID重复Div

时间:2016-08-01 09:44:59

标签: javascript jquery

我有一个复制div的函数,并将新div id增加1

function duplicate(){
    // Get content to clone
    var line_to_clone = $('#fields_1').html();
    // Get new line id
    var next_line_id = $('.items').length + 1;
    // Add the div container
    var line_to_clone = '<div id="fields_' + next_line_id + '" class="items">' + line_to_clone + '</div>';
    // Create new line
    var new_line = line_to_clone.replace(/_1/gi, "_" + next_line_id);
    // Render it
    $('#renderer').append(new_line);
}

它会起作用但是当它碰到10时它们是错误的

<div id="fields_8" class="items">
<div id="fields_9" class="items">
<div id="fields_100" class="items">
<div id="fields_111" class="items">
<div id="fields_122" class="items">
<div id="fields_133" class="items">
<div id="fields_144" class="items">

2 个答案:

答案 0 :(得分:1)

请查看下面的代码段。

function duplicate(){
// Get content to clone
var line_to_clone = $('#fields_1').html();
// Get new line id
var next_line_id = $('.items').length + 1;
  
// Add the div container
var line_to_clone = '<div id="fields_' + next_line_id + '" class="items">' + line_to_clone + '</div>';
// Create new line

// Render it
$('#renderer').append(line_to_clone);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="renderer">
  <div id="fields_1" class="items">123</div>
</div>
<input type="button" value="add" onclick="duplicate()"/>

答案 1 :(得分:1)

或者你可以使用jQuery .clone() 函数,也可以使用jQuery :last 获取最后一项的id选择器然后在附加新项目的html之前将其增加1,如下所示:

<强> jsFiddle 1

$('#btn-foo').on('click', function() {
  var lastItem = $('#renderer .items:last'),
    lastID = parseInt(lastItem.attr('id').replace('fields_', ''));
  $('#renderer').append(lastItem.clone().attr('id', "fields_" + (lastID + 1)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn-foo">Add</button>
<hr>
<div id="renderer">
  <div id="fields_1" class="items"><span>Lorem ipsum dolor sit amet.</span>
  </div>
</div>

<强>更新

根据OP的评论,存在重复输入字段值的问题,idname属性的值也必须是唯一的,因此,{{3}我们把它们都固定了