为按钮创建的每个新行添加i++

Add i++ for each new row that will created by the button

本文关键字:新行 添加 i++ 按钮 创建      更新时间:2023-09-26

我尝试用PHP和Javascript制作一些可重复的字段。这工作得很好,但在保存帖子(为WordPress创建插件)后,克隆的行将覆盖最新的行。这是因为我没有为每一行使用唯一的id。

我想添加一个'id'属性与javascript,我想为每一行是与id 1增加创建。我已经用PHP做了类似的事情,但发现这不是我想要的,我用javascript更好,我想,因为当我用"添加新"按钮克隆字段时,数量不会增加+1;

下面是我使用的php代码:
$count = 2;
for ($i = 0; $i < $count; $i++) {
    // Begin a table row
    echo '<tr class="row" id="' . '['.$i.']' . '-repeatable">';
    echo '<td class="order">' . '['.$i.']' . '</td>';
            // Do cool stuff inside the row
    echo '<td class="remove"><a class="repeatable-remove button" href="#">-</a></td>';
    echo '</tr>'; // End .row
} // End for loop
<a href"#" class="button">Add new row</a>
可重复字段的JS代码:
// Add repeatable row
jQuery('.repeatable-add').click(function() {
    // Clone row
    var row = jQuery(this).closest('.ui-sortable').find('tbody tr.row:last-child');
    var clone = row.clone();
    clone.find('input[type=text], text, textarea, select, input.upload_image').val(''); // Reset the values
    clone.find('.preview_image').attr('src', ''); // Reset the values
    row.after(clone);
    //
    return false;
});

我想我必须做一些像这样的代码片段:

clone.find('tr.row').attr('id', 'repeatable-' + addInteger);

但是我如何在Jquery/Javascript中增加+1,就像我在PHP中的例子?

您要做的是查看要克隆的行的ID,并使用该ID为新行提供适当的索引值。我在示例中添加了两行代码,一行定义一个名为clonedIdIndex的新变量,另一行使用该变量中的值为克隆行定义一个新ID。

jQuery('.repeatable-add').click(function() {
    // Clone row
    var row = jQuery(this).closest('.ui-sortable').find('tbody tr.row:last-child'),
        clone = row.clone(),
        clonedIdIndex = parseInt( clone.find('tr.row').attr('id').split('-')[1], 10 );
    clone.find('input[type=text], text, textarea, select, input.upload_image').val('');    
    clone.find('.preview_image').attr('src', ''); // Reset the values
    // Assign new ID
    clone.find('tr.row').attr('id', 'repeatable-' + (++clonedIdIndex));
    row.after(clone);
    //
    return false;
});