繁体   English   中英

动态HTML页面内容

[英]Dynamic HTML page content

假设我想在每次用户更改搜索选项时显示不同的项目。 我通过AJAX获取新项目(这是强制性的,所以我不能使用POST,所以我不能使用django模板的{%for%}循环)。 目前,我获取返回的项目列表,并将其传递给生成HTML代码的javascript函数。 此函数不仅仅是将字符串连接在一起并形成新的HTML内容。

一个简单的例子:

function build_items_list(items_list, container){
    container.innerHTML = '';
    for(var i=0; i<items_list.length; i+=1){
        var item = items_list[i];
        container.innerHTML += '<div>' +
                               '<input type="checkbox" id="' + item.id.toString() + '">' + 
                               '<a href="' + item.url+'"><b>' + item.name + '</b></a>'+
                               '</div>'

    }
}

显然,它不是生成内容的最佳方式,我有许多类似的内容要生成。

生成此类内容的正确方法是什么?

非常感谢你。

首先,没有正确的方法。
你这样做的方式很好。
话虽这么说,我不得不在JavaScript中多次创建内容,因此想出了一个生成内容的功能。 它可以很容易地修改,我发现它保持代码,imo,更清洁。

function createElement(element, attributes, text) {
    // function to create an element with class and text if wanted.
    // attributes is an object of key value items. Key is the attribute, value is the value.
    // you could change the "class" to an argument and use it to set anyAttribute
    var el = document.createElement(element);
    $.each(attributes, function(key, value) {
        el.setAttribute(key, value);
    });
    if (text) {
        var t = document.createTextNode(text);
        el.appendChild(t);
    }
    return el;
}

例如,上面的内容可以这样调用:

createElement("div", { 
    "class": "btn btn-default btn-sm btn-gene col-md-4", 
    "value": value }, "remove item")

这会创建以下元素

<div class"btn btn-default btn-sm btn-gene col-md-4" value="value">remove item</div>

你仍然会在JavaScript中构建元素并将它们附加到DOM,这有点工作,但我发现它有助于DRY。

在另一方面,您可以使用,如@Or Duan所说,前端框架或者,您可以使用前端模板引擎。
框架通常包含模板引擎和数据绑定值,以便它们在值更改时更改,但您可以自己执行逻辑并只使用框架外的模板引擎。
根据您的需求,有各种模板引擎 - https://garann.github.io/template-chooser/

对不起,但没有简单的解决方案,这就是为什么像Angular,Ember等库这么成功的原因,你可以将js变量绑定到模板中。

您可以像编写每个模板一样编写许多函数,但考虑使用第3方库。

角度代码示例:

<div ng-repeat="item in items_list">
    <div>
        <input type="checkbox" id="{{item.id}}">
        <a href="{{item.url}}"><b>{{item.name}}</b></a>
    </div>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM