[英]How do I create an HTML element with attributes and events using JavaScript?
[英]How do I conventionally create a replica of an element as a new element in HTML using JavaScript (jQuery)?
小提琴: 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');
這應該可以解決問題。
工作小提琴: 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標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.