如何复制表格的特定部分?

时间:2018-10-15 05:00:35

标签: javascript jquery html

我有一些代码,如下例:

<form>
  <label>name</label><input type="text" />
  <label>phone</label><input type="text" />

  <label>color</label><select>
    <option>red</option>
    <option>blue</option>
    <option>green</option>
  </select>

  <label>e-mail</label><input type="text" />
</form>

如果用户需要通过select部分和电子邮件输入字段之间的按钮来复制select部分,我想只复制它。

我不是真的很喜欢JavaScript或jQuery,因此,如果您也可以在答案中添加清晰的解释,将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以使用JQuery clone函数来克隆您的元素,然后将其附加到需要的位置,或者如果需要为每个部分使用不同的ID,则可能需要保存索引并进行设置每次添加栏目时作为ID

var index = 1;
function addColor() {
  var nextSection = '<div id="color-section-' + index++ + '">' +
    '<label>color</label>' +
    '<select>' +
      '<option>red</option>' +
      '<option>blue</option>' +
      '<option>green</option>' +
    '</select><br />' +
  '</div>';
  $(nextSection).appendTo($("#color-section"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form">
  <label>name</label><input type="text" /><br />
  <label>phone</label><input type="text" /><br />

  <div id="color-section">
    <label>color</label>
    <select>
      <option>red</option>
      <option>blue</option>
      <option>green</option>
    </select><br />
  </div>

  <label>e-mail</label><input type="text" /><br />
</form>

  <button onClick="addColor()">Add Color</button><br />

答案 1 :(得分:1)

您可以使用clone()复制元素。参见下面的示例并进行解释。

  1. 名称为“ color-selections”的div元素包含一个初始选择标签。

    <div class="color-selections"> <select> <option>red</option> <option>blue</option> <option>green</option> </select> </div>

  2. “ color-selections”类中将没有未知数量的select标签。因此,我使用first()方法获取第一个元素(原始选择标签)。

    $(".color-selections select:first")

  3. 使用clone()复制第一个元素。

    $(".color-selections select:first").clone()

  4. 最后,使用appendTo()方法将此克隆元素附加到“颜色选择”类中。

    $(".color-selections select").first().clone().appendTo(".color-selections");

function addColor() {
  $(".color-selections select:first").clone().appendTo(".color-selections")
  //OR $(".color-selections select").first().clone().appendTo(".color-selections");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>name</label><input type="text" />
  <label>phone</label><input type="text" />

  <label>color</label>
  <div class="color-selections">
    <select> //$(".color-selections select:first")
      <option>red</option>
      <option>blue</option>
      <option>green</option>
    </select>
  </div>
  <input type="button" value="+" onclick="addColor();">

  <label>e-mail</label><input type="text" />
</form>

我希望设计不是示例代码的重要组成部分。

相关问题