Deleting row in table with Jquery in mvc project

前端 未结 4 1302
感情败类
感情败类 2021-01-06 15:55

I generate the following html code


        @for (int i = 0; i < Model.listUsers.Count; i++)
        {
            
相关标签:
4条回答
  • 2021-01-06 16:18

    You are generating duplicate id attributes for your button which is invalid html and the script will only be called once because you then delete the button. Instead remove the id and use a class name instead

    <button type="button" class="delete" data-id="@Model.listUsers[i].ID">Delete</button>
    

    and modify the script to

    $(".delete").on("click", function () {
      var tr = $(this).closest('tr');
      tr.remove();
    });
    
    0 讨论(0)
  • 2021-01-06 16:23

    You are rendering a button with same id multiple times which is invalid html and every time you apply a selector on it, it selects the first element it finds in DOM with id deleted. Make the id unique by appending the id that is coming in Model and add a class attribute to the button:

    <button type="button" class="delete" id="delete_@(Model.listUsers[i].ID)" data-id="@Model.listUsers[i].ID">Delete</button>
    

    Now apply a click event on the class:

    $(".delete").on("click", function () {
        var tr = $(this).closest('tr');
        tr.remove();
    });
    
    0 讨论(0)
  • 2021-01-06 16:38

    replace this id with class because the id duplicate

    <script type="text/javascript">
     $(document).ready(function(){
      $(".delete").on("click", function () {
                var tr = $(this).closest('tr');
                    tr.remove();
                });
     });
    
    
    </script>
    
    <tr>
    
    <td> @Html.DisplayFor(m => m.listUsers[i].Name)</td>
    <td>   @Html.DisplayFor(m => m.listUsers[i].Phone) </td>
    <td>
        <button type="button" class="delete" data-id="@Model.listUsers[i].ID">Delete</button>
    </td>
    

    0 讨论(0)
  • 2021-01-06 16:40

    IDs in HTML must be unique, use a class instead then you can use Class Selector (".class").

    Selects all elements with the given class.

    HTML

    <button type="button" class="delete" data-id="@Model.listUsers[i].ID">Delete</button>
    

    Script

    $(document).ready(function () {
        $(".delete").on("click", function () {
            var tr = $(this).closest('tr');
            tr.remove();
        });
    }); 
    
    0 讨论(0)
提交回复
热议问题