将模板预先添加到div中的img

时间:2015-07-16 11:39:58

标签: javascript jquery html html5 append

我需要动态地将模板放在静态img上面,它位于div中。为了在运行两次函数模板(){}后更加精确,我希望我的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>

运行两次功能模板(){}之后,我的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);

    })

}
你能帮帮我吗?

3 个答案:

答案 0 :(得分:1)

问题是:

  • .append()将数据附加到元素的末尾。
  • .prepend()将数据添加到元素的开头。

使用.prepend()代替.append()

parent.prepend(template);

而且,复制id并不是一个好主意,因为它们是唯一的。最好在添加数据之前更改ElementID

答案 1 :(得分:1)

您可以使用.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。使用类而不是它。

答案 2 :(得分:1)

使用$.prepend代替$.append,同时id 必须 是唯一的(<div id="templateID"></div>),更改它上课

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>