简体   繁体   English

使用 jquery/javascript 附加带有变量的 html 代码

[英]Append html code with variables using jquery / javascript

I am having trouble generating html code from jqavascript/jquery in a html template rendered in django.我无法在 django 中呈现的 html 模板中从 jqavascript/jquery 生成 html 代码。 I have to append html code and also insert some values in between.我必须附加 html 代码并在它们之间插入一些值。 Right now I am doing a crude string append like this现在我正在做这样一个粗略的字符串追加

var features =['a','b']
for (var i=0;i<features.length;i++){
    var html_code = "<div class = 'feature' <h2>"+features[i]+"</div>
    $("#features").append(html_code)
}

For html code对于 html 代码

<div id="features"></div>

What is the right and cleanest way to do this.什么是正确和最干净的方法来做到这一点。 I know templating is the way to go but there seem to be so many different ways - inline javascript, external library like mustache,handlebar, using django's own template solution - it's very confusing我知道模板是要走的路,但似乎有很多不同的方法 - 内联 javascript,像 mustache、handlebar 这样的外部库,使用 django 自己的模板解决方案 - 这非常令人困惑

You have indeed a wide range of options for this.为此,您确实有多种选择。 I'd make the decision based on how many times do you need to change the DOM in your website.我会根据您需要更改网站中的 DOM 多少次来做出决定。 If it is very often, I'd think about using a library to make it more readable/maintainable (React + ReactDOM is very lightweight, 31,8kB gzipped according to this gist )如果经常使用,我会考虑使用一个库来使其更具可读性/可维护性(React + ReactDOM 非常轻量级,根据这个gist 压缩了 31,8kB)

If you have to insert the html in one or two places and you care about performance, check this article如果您必须在一两个地方插入 html 并且您关心性能,请查看这篇文章

Keep in mind that in each iteration you are traversing the DOM to find the #features element and that's very inefficient.请记住,在每次迭代中,您都在遍历 DOM 以查找#features元素,这是非常低效的。 It'd be better to perform the query outside the loop and store it in a const, or do it like shown below.最好在循环外执行查询并将其存储在常量中,或者像下面所示那样执行。

Also, it might be a typo, but you have a sneaky h2 tag there <div class = 'feature' <h2> .此外,这可能是一个错字,但是您在<div class = 'feature' <h2>有一个偷偷摸摸的 h2 标签。 Modern browsers try to fix HTML errors but you should not rely on it because they have to do a lot of guesswork and it might break your layout.现代浏览器尝试修复 HTML 错误,但您不应该依赖它,因为它们必须进行大量猜测并且可能会破坏您的布局。

TL;DR TL; 博士

Fastest way is with vanilla JS:最快的方法是使用 vanilla JS:

const features = ['a', 'b']
const c = document.createDocumentFragment();
for (let i=0; i<features.length; i++) {
    const e = document.createElement("div");
    const textNode = document.createTextNode(features[i]);
    e.appendChild(textNode);
    e.className = "feature";
    c.appendChild(e);
}
document.querySelector('#features').appendChild(c);

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

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