我如何使用JavaScript(jQuery)在HTML中以传统方式创建元素的副本作为新元素

How do I conventionally create a replica of an element as a new element in HTML using JavaScript (jQuery)?

本文关键字:元素 副本 创建 新元素 方式 JavaScript 何使用 jQuery HTML 传统      更新时间:2023-09-26

小提琴:https://jsfiddle.net/b8fr76cb/

我想通过单击导航栏中的"新建"按钮有效地创建一个新框。我在网上看到建议不要使用长 HTML 字符串并以这种方式附加元素,因此,就我有限的知识而言,这排除了从一开始就创建自定义框的可能性。因此,我看到两个选项:

  1. 制作当前框的副本(始终至少有一个,因为从一开始就会有一个默认的)并根据个别情况调整属性。

  2. 有一个隐藏的"骨架"框,我复制它,然后根据个别情况调整属性。但是,我不确定此选项是常规的还是允许的,还是丑陋的或任何其他形容词。

请告知以下哪个是更好的选择,或者是否有更好、更值得推荐的选择。

下面是该框的 HTML:

<ul class="list-group box">
  <li class="list-group-item text-right box-title-area">
    <h4 class="box-name not-selectable">Title</h4>
    <span class="glyphicon glyphicon-pencil rename-box" aria-hidden="true"></span>
  </li>
  <li class="list-group-item rename-box-controls">
    <div class="input-group">
      <input type="text" class="form-control new-name">
      <div class="input-group-btn">
        <button type="button" class="btn btn-default confirm-change-name"><span class="glyphicon glyphicon-ok"></span></button>
        <button type="button" class="btn btn-default cancel-change-name"><span class="glyphicon glyphicon-remove"></span></button>
      </div>
    </div>
  </li>
  <li class="list-group-item not-selectable">
    Entry1
    <span class="badge">10</span>
  </li>
  <li class="list-group-item not-selectable">
    Entry2
    <span class="badge">10</span>
  </li>
  <li class="list-group-item not-selectable">
    Entry3
    <span class="badge">10</span>
  </li>
  <li class="list-group-item btn-group buttons" role="group">
    <button type="button" class="btn btn-success">Button1</button>
    <button type="button" class="btn btn-primary">Button2</button>
    <button type="button" class="btn btn-info">Button3</button>
  </li>
</ul>

以下是我需要完成的 JavaScript 函数的骨架代码:

$('#new-box').click(function() {
 /* Code to add new box alongside the last one. */
});
您可以使用

jQuery.clone()函数。

var element = $(".myBox").clone();
// Do your modifications to the box here.
$(element).find('.removeThisRow').remove(); // For example remove a row from the box
$(element).appendTo('#myBoxContainer');

这应该可以解决问题。

工作小提琴:https://jsfiddle.net/b8fr76cb/1/

您可以使用一个简单的语句来获取您的要求。

$('#new-box').click(function() {
    $("#first-row").parent().append('<div class="col-xs-6 col-md-2">'+$("#first-row").html()+"</div>");
  });

使用 .parent() 来定位克隆元素,并使用 .append() 在可用的 html 代码之后创建 html 标记。