删除任何元素,然后重新分配计数值 [英] Deleting any element, the reassigning the count value

查看:58
本文介绍了删除任何元素,然后重新分配计数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,标题难以描述!

Sorry about the cryptic title, it's hard to describe!

单击按钮时,我正在使用以下脚本在表单中添加一行:

I am using the following script to add a row to my form when a button is clicked:

  $(document).ready(function() {
      $('#btnAdd').click(function() {
        var num     = $('.clonedInput').length;
        var newNum  = new Number(num + 1);

        var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);

        newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
        $('#input' + num).after(newElem);
        $('#btnDel').attr('disabled','');

        if (newNum == 5)
            $('#btnAdd').attr('disabled','disabled');
      });

      $('#btnDel').click(function() {
        var num = $('.clonedInput').length;

        $('#input' + num).remove();
        $('#btnAdd').attr('disabled','');

        if (num-1 == 1)
            $('#btnDel').attr('disabled','disabled');
      });

      $('#btnDel').attr('disabled','disabled');
  });

这绝对可以正常工作,但是您只能删除最后添加的行不是非常用户友好.假设我要删除之前添加的行,则必须删除此后要执行的所有操作.

This works absolutely fine, but it's not very user-friendly that you can only delete the last added row. Say I want to delete a row added earlier on, I would have to delete everything I'd done since then.

如何删除任何行,同时将计数值重新分配给其他行,以使计数仍然是连续的(即,Row1,Row2,Row3等,而不是Row1,Row5,Row8)?/p>

How can I delete any row, and at the same time reassign the count value to the other rows, so that the count is still sequential (i.e. Row1, Row2, Row3 etc, rather than Row1, Row5, Row8)?

推荐答案

我建议您不要为元素明确设置ID.相反,您可以使用jQuery功能强大的选择器来获取元素的位置.

I recommend that you don't explicitly set an id to the elements. Instead you can use jQuery powerful selectors to get the position of an element.

这是一个基于常见html结构的示例.发布您自己的html,为您提供更多详细信息.

This is an example, based on a common html structure. Post your own html to give you a more details.

  $('.btnDel').click(function() {
    var num = $(this).parent().prevAll().size();

    // this points to delete link.
    // The previous element is the content element
    $(this).prev().remove();

    $('#btnAdd').attr('disabled','');

    if (num-1 == 1)
            $(this).attr('disabled','disabled');
  });

<div class='elem'>
  <span class='content'>....</span>
  <a class='btnDel' href='#'>Delete</a>
</div>

这篇关于删除任何元素,然后重新分配计数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆