javascript - JQuery 克隆递增 id 没有出现序列并且也删除行

标签 javascript jquery html jquery-ui

当前正在工作的 jQuery 克隆,其中我使用当前代码增量为整个 div 增量 id 正在工作,但不是按顺序 expy -1,如果用户单击“添加更多”按钮,它会生成随机 id 号 expy-3。因此,当我添加行时,我想用我的代码删除该行,我可以删除该行,但 id 不会递减,例如,如果我有 expy-1、expy-2、expy-3,如果我删除 expy-2 expy-3 id 必须更改 expy-2,因为我已经有了 expy1

这是jquery代码

$(document).on("click", ".exp_add_button", function() {
var $clone = $('.cloned-row3:eq(0)').clone(true, true);
var num = $('.cloned-row3').length;
$clone.find(".chk_Field_exp").val('');
  $clone.find('[id]').each(function() {
    this.id += '_' + num;
    $(this).removeClass("errRed");
    if ($(this).hasClass("required_Field")) {
      $(this).prevAll('label').find('span.required-star').removeClass('text-error-red');
      $(this).addClass("cloned_field");
    } else {
      $(this).removeClass("errRed");
      $(this).removeClass("text-error-red");
    }
  });
$clone.find('.btn_more').after("<input type='button' class='btn_less1 edu_btnle' id='buttonless" + (++rowCount) + "'/>")
$clone.attr('id', "expy-" + (++rowCount)).addClass('exp_add');
$clone.find(".startDate").val('');  
$clone.find(".endDate").val('');
/*$clone.find(".degree_Description").attr('disabled', true).val('');*/
$clone.find(".startDate,.endDate")
  .removeClass('hasDatepicker')
  .removeData('datepicker')
  .datepicker({
    dateFormat: "mm/dd/yy",
    changeMonth: true,
    yearRange: "-100:+0",
    changeYear: true,
    maxDate: new Date(),
    showButtonPanel: false,

    beforeShow: function() {
      setTimeout(function() {
        $('.ui-datepicker').css('z-index', 99999999999999);

      }, 0);
    }
  });

$(this).parents('.wrk_exp').after($clone);
});

这是删除代码

  $(document).on('click', ".btn_less1", function() {
var len = $('.cloned-row3').length;
if (len > 1) {
  $(this).closest(".btn_less1").parent().parent().parent().remove();
}

});

这是fiddle link

提前致谢

最佳答案

这是因为您在这两行中将 rowCount 的值增加了两次:

$clone.find('.btn_more').after("<input type='button' class='btn_less1 edu_btnle' id='buttonless" + (++rowCount) + "'/>")
$clone.attr('id', "expy-" + (++rowCount)).addClass('exp_add');

从底部的rowCount中删除一个++,代码将是:

$clone.find('.btn_more').after("<input type='button' class='btn_less1 edu_btnle' id='buttonless" + (++rowCount) + "'/>")
$clone.attr('id', "expy-" + (rowCount)).addClass('exp_add');

Fiddle

++rowCount 更改 rowCount 的值并等于

rowCount = rowCount+1

关于javascript - JQuery 克隆递增 id 没有出现序列并且也删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34392379/

相关文章:

javascript - 使用 isNumeric 检查输入中的数字

javascript - RXJS - 如果可观察值中的值满足特定条件,则执行函数

javascript - 从函数返回 json 对象

javascript - 用jquery将div点击链接到另一个div?

javascript - Strongloop - 使用 model.js 执行 PHP

javascript - Node.js 正在捉弄我。使用数组生成随机名称和推文

javascript - 从两个表中获取值。 - Sequelize

javascript - 在警报框中调用变量

jquery - 当我将语言更改为阿拉伯语时,Highcharts 图例重叠

html - 修复布局 Flexbox