[英]Prepending template to img inside div
我需要將模板動態放置在位於div中的靜態img上方。 為了更精確地執行兩次函數template(){},我希望我的HTML代碼像這樣:
<div class="main">
<div id="templateID"></div>
<div id="templateID"></div>
<img src="~/Content/img/preload.gif" id="gifLoad"/>
</div>
在運行之前,我的HTML如下所示:
<div class="main">
<img src="~/Content/img/preload.gif" id="gifLoad"/>
</div>
兩次運行函數template(){}之后,我的HTML如下所示:
<div class="main">
<img src="~/Content/img/preload.gif" id="gifLoad"/>
<div id="templateID"></div>
<div id="templateID"></div>
</div>
假設在img上方添加模板的功能如下所示。
function template(data) {
var parent = $('.main');
var template = '<div id="templateID"></div>';
var parent2 = $('#gifLoad');
$('template').prependTo(parent2);
parent.append(template);
})
}
你能幫我嗎?
問題是:
.append()
將數據追加到元素的末尾。 .prepend()
將數據添加到元素的開頭。 使用.prepend()
而不是.append()
:
parent.prepend(template);
而且,復制id
也不是一個好主意,因為id
是唯一的。 最好在添加數據之前更改ElementID
。
您可以使用.append
var parent = $('.main');
var template = '<div class="templateID"></div>';
parent.prepend(template.clone());
parent.prepend(template);
或使用.before()
var template = '<div class="templateID"></div>';
$("#gifLoad").before(template);
$("#gifLoad").before(template.clone());
*不得使用重復的ID。 使用類代替它。
使用$.prepend
代替$.append
,而且id
必須是唯一的( <div id="templateID"></div>
),將其更改為class
function template(data) { var parent = $('.main'); var template = '<div class="templateID"></div>'; parent.prepend(template); } template(); template();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main"> <img src="~/Content/img/preload.gif" id="gifLoad"/> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.