如何打造“大"JavaScript(JQuery)中的div结构?

2022-01-22 00:00:00 append jquery javascript html

我需要制作大的 DIV 结构并将它们附加到包装器中.但到目前为止,我所看到的总是将 一个 DIV 元素附加到另一个元素中.

I need to make big DIV structures and append them to a wrapper. But what I've seen so far was always about appending one DIV element into another one.

有一个空的 DIV-Wrapper,用大"DIV-Elements 填充

There is an empty DIV-Wrapper, to be filled with "big" DIV-Elements

<div class="PostWrapper">
    // Content should be added to here
</div>

我想附加到 PostWrapper 的 DIV 元素如下所示:

The DIV-Elements which I want to append to the PostWrapper look like this:

<div class="Post">
    <div class="PostHead">
         <span class="profilePicture">
             <img src="../Profiles/Tom.jpg" />
         </span>
         <span class="userName">Tom</span>
         <span class="postTime">10 minutes ago</span>
    </div>
    <div class="PostBody">
        <p>Hey Tom, great work at the presentation last week. Well done!</p>
    </div>
</div>

所以这是一个 DIV 结构的示例,我想构建并存储在一个 javascript 变量中并附加到我的包装器中,例如:

So this is an example of a DIV-Structure which I'd like to build and store in a javascript Variable and append to my wrapper like:

var postElement = $("div", {class: "Post"}).append("div", {class: "PostHead"}).append("div", {class: "PostBody"})......

这不会像预期的那样工作.但是我想不出一个简单的方法来避免过于复杂的代码.

This wont work like expected ofc. But I can't think of a simple way of doing this without having overly complexe code.

这怎么可能?

推荐答案

对于任何复杂的东西,使用 HTML 模板.这可以像一个带有 id 的虚拟脚本块一样简单,它使用未知类型,因此浏览器会忽略它(我使用文本/模板).然后,您只需使用元素的内部 html() 来创建新结构.更容易阅读/维护,更不容易出错

For anything complex, use a HTML template. That can be as simple as a dummy script block, with an id, that uses an unknown type so the browser ignore it (I use text/template). You then just use the inner html() of the element to create the new structure. Much easier to read/maintain and less error prone

示例 html:

<script id="mytemplate" type="text/template">
    <div class="Post">
        <div class="PostHead">
             <span class="profilePicture">
                 <img src="../Profiles/Tom.jpg" />
             </span>
             <span class="userName">Tom</span>
             <span class="postTime">10 minutes ago</span>
        </div>
        <div class="PostBody">
            <p>Hey Tom, great work at the presentation last week. Well done!</p>
        </div>
    </div>
<script>

然后创建一个:

$('.PostWrapper').append($('#mytemplate').html());

注意:如果他们在任何地方需要动态值,请在模板中使用文本替换标记并替换字符串.

例如

<script id="mytemplate" type="text/template">
    <div class="Post">
        <div class="PostHead">
             <span class="profilePicture">
                 <img src="{image}" />
             </span>
             <span class="userName">{name}</span>
             <span class="postTime">{posted}</span>
        </div>
        <div class="PostBody">
            <p>{notes}</p>
        </div>
    </div>
<script>

或者在模板添加到 DOM 后简单地添加这些细节.

Or simply add those details once the template has been added to the DOM.

相关文章