如何创建每次用户点击时附加列的表格

时间:2017-10-31 02:56:55

标签: javascript jquery html dom html-table

我想在html中创建一个表,每次用户点击它时都会添加一列(起始列数:1)。

所以理想情况下,如果用户点击表6次,表格应如下所示: enter image description here

这是我的HTML和js:

<!DOCTYPE html>
<html>
<body>
<head>
    <title></title>
    <script link src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link rel="stylesheet" href="jquery-ui.min.css">
    <link rel = "stylesheet" type" type="text/css" href = "style.css">
    <script src="jquery-ui.min.js"></script>
    <table id = "table" style="width: 100%; height: 100px; border-style: solid">
        <tr>
            <th class = "column"></th>
        </tr>
</head>
</body>
</html>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
    $("#table").click(function()
    {
        var column = document.createElement("TH")
        column.className = "column";
        document.getElementById("table").appendChild(column);   
    });
});
</script>

相反,当用户点击6次时会发生什么: enter image description here

用户点击时似乎正在创建一个新行。有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:0)

您可以使用解决方案

$(document).ready(function() {
  $("#table").click(function(){
    $(this).find('tr').append("<th class='column'></th>");   
  });
});
.column {
  border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "table" style="width: 100%; height: 100px; border-style: solid">
  <tr>
      <th class = "column"></th>
  </tr>
</table>

希望这会对你有所帮助。

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<head>
<title>Add Coulmn</title>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.head {
  border: 1px solid ;
  background:#AEB6BF;
}
.column {
  border: 1px solid ;
  background:#EAEDED;

}
</style>
<script>
$(document).ready(function() {
  $("#btnAdd").click(function(){

    var CoulmnCount=$("table > tbody > tr:first > td").length+1;

    $("#table").find('thead').find('tr').append("<th class='head'>header"+CoulmnCount+"</th>");   
     $("#table").find('tbody').find('tr').append("<td class='column'>Coulmn1"+CoulmnCount+"</td>");  
  });
});
</script>
</head>
<body>

<input type="submit" value="Add Coulmn" id="btnAdd">
<table id = "table" style="width: 100%; height: 30px; border-style: solid">
  <thead>
  <tr>
      <th class = "head">Header1</th>
  </tr>
   </thead>
   <tbody>
   <tr>
      <td class = "column">Coulmn1</td>
  </tr>
   </tbody>
</table>
</body>
</html>