HTML表格行ID复选框

时间:2019-05-17 08:18:25

标签: javascript php html mysql ajax

我希望每行都有数据库表ID作为动态html表的复选框值

我正在使用ajax从mysql数据库中获取数据,并创建一个新的变量作为html文本添加到表的正文中

HTML代码

<div class="col-sm-6" id="ftbl">
    <label for="urbandata">View urban data</label>
    <table class="table table-bordered table-striped">
      <thead>
        <tr>
          <th>Check</th>
          <th>ID</th>
          <th>Type</th>
          <th>Master</th>
          <th>Slave</th>
          <th>Orbit</th>
          <th>Mode</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
</div>

JS代码

$.ajax({
    url: "fetchurban.php",
    method: "POST",
    data:{id:id},
    dataType: "JSON",
    success: function(data){
      if (data){
      var trHTML = '';
        $.each(data, function (i, item) {
            trHTML +='<tr><td><input type="checkbox" id="checkview" onclick="QuickView()" name="'+ item.TblID +'"></td><td>' + item.Type + '</td><td>' + item.Master + '</td><td>' + item.Slave + '</td><td>' + item.Orbit + '</td><td>' + item.Mode + '</td><td><a href='+ item.ImgTIF+ ' title="Download High Quality" data-toggle="tooltip"><span class="glyphicon glyphicon-download"> </span></a><a href=#?id='+ item.ImgLow + ' title="Download Low Quality" data-toggle="tooltip"><span class="glyphicon glyphicon-cloud-download"></span></a></td></tr>' ;
        });
        $('#ftbl tbody').append(trHTML);
      }
    }
  })
})

如果用户选中该复选框,则我希望获得数据库表的ID。 现在,使用此代码,我对表的所有行都具有相同的ID

1 个答案:

答案 0 :(得分:1)

您可以将标识符设置为输入的data-元素:

function QuickView(element) {
  var rowId = $(element).data('id');
  // here comes the rest of your code.
}

$.ajax({
    url: "fetchurban.php",
    method: "POST",
    data:{id:id},
    dataType: "JSON",
    success: function(data){
      if (data){
      var trHTML = '';
        $.each(data, function (i, item) {
            trHTML +='<tr><td><input type="checkbox" data-id="'+ item.TblID +'" onclick="QuickView(this)"></td><td>' + item.Type + '</td><td>' + item.Master + '</td><td>' + item.Slave + '</td><td>' + item.Orbit + '</td><td>' + item.Mode + '</td><td><a href='+ item.ImgTIF+ ' title="Download High Quality" data-toggle="tooltip"><span class="glyphicon glyphicon-download"> </span></a><a href=#?id='+ item.ImgLow + ' title="Download Low Quality" data-toggle="tooltip"><span class="glyphicon glyphicon-cloud-download"></span></a></td></tr>' ;
        });
        $('#ftbl tbody').append(trHTML);
      }
    }
  })
})

以下是上述demo

编辑:

我删除了关于不允许将整数用作ID属性的初始句子,因为该属性不再有效,正如昆汀在评论中指出的那样。有时很难忘记您曾经学到的东西。