【问题标题】:How to add copy a whole column to an html table with jQuery?如何使用 jQuery 将整列复制到 html 表中?
【发布时间】:2016-05-26 23:26:49
【问题描述】:

我想在 html 表单中创建一个 html 表,其列数取决于用户将输入的变量。这是我很难工作的脚本的摘录。不幸的是,事实并非如此。

var nbrCofondateur = 5;
var nbrColonne = 2; 

function tabGenerateur()
{
 
while (nbrCofondateur>nbrColonne) {
 	
 $("#col1").clone().appendTo("#col1").parent(); 
$("#col2").clone().appendTo("#col2").parent(); 
 
 nbrColonne++; 
}

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <h1>Calculatrice d'équité</h1>
  <p>Remplissez ce formulaire pour déterminer quel pourcentage d'équité chacun des co-fondateurs de votre start-up devraient recevoir.</p>
</div>

<div class="container-fluid" class="deuximeFormulaire">
<form>
 <table id="myTable">
  <tr id="cofondateursListe" >
    <th></th>
    <th>Cf 1</th>
    <th id="col1">Cf 2</th>
  </tr>
  <tr>
    <td>Quel est le taux horaire que le co-fondateur pourrait exiger sur le marché du travail?</td>
     <td><input style="width:100%" type="number" id="q1-cf1"></td>
      <td id="col2"><input style="width:100%" type="number" id="q1-cf2"></td>
  </tr>
 
</table> 
 <button type="submit" class="Submit" onclick="tabGenerateur();">Soummettre</button>
</form>
</div>

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。
  • 我可能明白你想要什么。您不必将parent() 放在append() 之后,而且您不应拥有多个具有相同ID 的元素,这正是您通过复制元素所做的事情。
  • @ZakariaAcharki,标题还不够清楚吗?
  • 您的代码不够清晰,无法反映您在标题中的内容。

标签: javascript jquery html html-table


【解决方案1】:

$("button").click(function () {
  $("tr > :last-child").each(function () {
    var $this = $(this);
    $this.clone().appendTo($this.parent());
  });
});
table { width: 100%; table-layout: fixed; margin-bottom: .5em; }
table, tr, th, td { border: 1px solid; }
th:first-child { counter-reset: th, td; }
th { counter-increment: th; }
th:after { content: "Col " counter(th); }
td:first-child { counter-increment: td; }
td:after { content: "Row " counter(td); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr><th>A <th>B </tr>
  <tr><td>C <td>D </tr>
  <tr><td>E <td>F </tr>
</table>

<button>Add column</button>

【讨论】:

  • 非常感谢!我使用它,但我有一个小问题。列的计数从 1 开始,但第一列填充的是描述,而不是实际元素,所以我不想在第一列上方显示任何内容。但是,当我将计数器的值设置为 -1 时,所有列都列为 Col 0。你能帮忙吗?
  • @JulienBrault,代码没有使用计数器——它只是一个演示。
猜你喜欢
  • 2020-02-03
  • 1970-01-01
  • 2012-05-27
  • 2013-11-09
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 2021-11-20
相关资源
最近更新 更多