fiddle :https://jsfiddle.net/b8fr76cb/
我想通过单击导航栏中的“新建”按钮来有效地创建一个新框。我在网上看到建议不要使用长 HTML 字符串并以这种方式附加元素,因此,据我所知,这排除了从一开始就创建自定义框的可能性。因此,我看到两个选项:
复制当前框(总是至少有一个,因为从一开始就有一个默认框)并根据具体情况调整属性。
<有一个我复制的隐藏“骨架”框,然后根据个别情况调整属性。但是,我不确定这个选项是传统的还是允许的还是丑陋的还是任何其他形容词。
请告知哪一个是更好的选择,或者是否有更好、更值得推荐的选择。
这是盒子的 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');
这应该可以解决问题。
关于javascript - 我如何使用 JavaScript (jQuery) 按照惯例在 HTML 中创建一个元素的副本作为新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36106076/