当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Dynamically remove row and update indices

问题描述:

I have a page where a user can add a row of information:

 <div id="refItem">

FirstName

LastName

</div>

users can keep pressing the add button and it will then keep appending to that div another row of data by manipulating the DOM. It also updates the ViewModel collection indices too. The ViewModel contains a collection of which has, FirstName and LastName as above

When the View loads, it uses the Model to render the data as above (so imagine a for loop rendering the row of data)

Question:

How can I delete the row from client side and update the indices at the same time before the user hits the submit button? what JQuery do I need to get hold of the row to delete and then update the DOM?

网友答案:

It depends on your exact markup, but in general:

  • use $(selector).remove() to delete the row
  • loop through the items and use $(this).prop("name", "value") to update the index.

Here's an example (Fiddle)

function del(index) {
    var toDelete = $("#refItem"+index);
    toDelete.remove();

    var id=1;
    // select all elements with id starting with "refItem", and loop
    $("div[id^=refItem]").each(function(item) {
        // update the "id" properties
        $(this).prop("id", "refItem"+id++);
    });
}

As an alternative, you could also put a button in each row, and remove it using a relative selector like (this).parent().remove(). (Fiddle).

分享给朋友:
您可能感兴趣的文章:
随机阅读: