[英]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.