在HTML表格的每一行上添加按钮的最简单方法

Easiest way to add a button on each row of a table HTML

本文关键字:一行 添加 按钮 最简单 方法 表格 HTML      更新时间:2023-09-26

我试图在HTML中创建一个表,作为每个行上的按钮,作为删除按钮。因此,当按钮被点击,它将删除html行以及行在数据库中。最简单的方法是什么?

这是我目前所拥有的,但它看起来一点也不好:

function GetSongs(id) {
    $.ajax(
    {
        type: "Get",
        url: "@Url.Action("GetSongs", "Game")",
        data: { playlistId: id },
        success: function (data) {
            json = data;
            var obj = JSON.parse(json);
            for (var i in obj) {
                songCount++;
                playlist.push(obj[i].SongURL);
                $("#song-table").append("<tr><td>" + obj[i].SongURL + "<button class=" +"editbtn" +">edit</button>"+ "</td></tr>");
            }
            $('#song-count').empty();
            $('#song-count').append('Song Count: ' + songCount);
        }
    });
}

这是我的表:

<div id="player-playlist" style="height: 300px; overflow:scroll; overflow-x: hidden">
      <table class="zebra" id="song-table" style="width:400px;">
              <tr>
                 <th>Song</th>
              </tr>
      </table>
</div>

你可以像添加编辑按钮一样添加删除按钮:

$("#song-table").append("<tr><td>" + obj[i].SongURL + "<button class=" +"delbtn" +">delete</button>"+ "</td></tr>");
$('button.delbtn').click(function(){
    $(this).parent().remove();
});
http://jsfiddle.net/qGGPZ/2/

给你的按钮一个包含id作为参数的onclick Javascript函数:

"<button type='button' onclick='deleteThisItem(" + id + ")' >delete</button>"

Javascript函数:

function deleteThisItem(theID){
    // ajax call to delete theID from database
    // refresh the table
}