[英]What's a clean and efficient way to generate and append HTML with JavaScript or JQuery?
I was going to ask this question (until I found it was already asked) and now have the answer to that question: 我打算问这个问题 (直到我发现它已被问到),现在得到了这个问题的答案:
It's better to request JSON from a PHP script and then wrap the results in HTML with JavaScript.
最好从PHP脚本请求JSON,然后使用JavaScript将结果包装在HTML中。
Now I have the unfortunate task of generating HTML with JavaScript to append to my document and am not sure how best to approach this. 现在我有一个不幸的任务,即使用JavaScript生成HTML以附加到我的文档中,并且不确定如何最好地处理这个问题。
With PHP I could simply store a HTML file and then use file_get_contents()
and regex to replace some tokens with the relevant information, however I don't think it's that easy with JavaScript. 使用PHP,我可以简单地存储一个HTML文件,然后使用
file_get_contents()
和regex用相关信息替换一些令牌,但是我不认为用JavaScript这么容易。
Some methods I have thought of: 我想到的一些方法:
The repulsive approach. 令人厌恶的方法。 Generate a massive ugly string and then append that:
生成一个巨大的丑陋字符串,然后附加:
var html = '<div class="comment">' + '<strong>' + author + '</strong>: ' + '<p>' + content + '</p>' + '</div>'; $("#comments").append(html);
Store the string somewhere and then use regex on that, which might look like this: 将字符串存储在某处,然后在其上使用正则表达式,这可能如下所示:
var commentHTML = '<div class="cmt"><strong>{auth}</strong>: {cmt}</div>';
Is there a library/plugin that deals with this better maybe? 是否有一个库/插件可以更好地处理这个? Riddling my JavaScript with chunks of HTML stored in strings is something I'd really like to avoid.
使用存储在字符串中的大量HTML来摆弄我的JavaScript是我真正想要避免的。 Maybe there is a similar method to what I mentioned I do using PHP?
也许我提到的使用PHP的方法有类似的方法? Can JavaScript read HTML files and store the content as a string?
JavaScript可以读取HTML文件并将内容存储为字符串吗?
Congrats, you just invented Mustache.js. 恭喜,你刚刚发明了Mustache.js。 Check it out: https://github.com/janl/mustache.js
看看: https : //github.com/janl/mustache.js
var data = { author: "An Author", content: "Some content" };
var template = "<div class='cmt'><strong>{{author}}</strong>: {{comment}</div>";
var html = Mustache.render(template, data);
You can inline templates as scripts with arbitary types 您可以将模板内联为具有任意类型的脚本
<script id="my-template" type="template">
<div class="comment">
<strong>%s</strong>:
<p>%s</p>
</div>
</script>
Writing a function to turn a "template" into a document fragment is trivial 编写将“模板”转换为文档片段的函数是微不足道的
function fragment(html) {
var args = arguments,
div = document.createElement('div'),
i = 1
div.innerHTML = html.replace(/%s/g, function(){
return String(args[i++])
})
return div.firstChild
}
Using it is also trivial 使用它也是微不足道的
fragment(document.getElementById("my-template").textContent, author, comment)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.