jquery - 如何使用 jQuery 创建和附加 HTML?
问题描述
我想知道如何使用 jQuery 创建和附加 HTML。显然,像这样编写 20-25 行甚至更多行代码是很乏味的:
"<h1>"+response.name+"</h1>" +
"<p>"+response.description+"</p>" + and so on
解决方案
如果你有一个(或多或少)固定的标记结构并且反复想用变量值填充它,你可以考虑使用模板。
有大量的 JS 模板引擎,但为了简单起见,这里有一个使用mustache.js的示例:
<script src="mustache.js" type="text/javascript"></script>
<script id="template" type="x-tmpl-mustache">
<h1>{{name}}</h1>
<p>{{description}}</p>
{{#optionalVar1}}
<p>{{#optionalVar1}}</p>
{{/optionalVar1}}
</script>
<script type="text/javascript">
var template = document.querySelector('#template').innerHTML;
/* "response" should be an object containing named members as
* in the template above. "{{name}}" refers to "response.name" */
var rendered = Mustache.render(template, response);
document.querySelector('#output').innerHTML = rendered;
</script>
推荐阅读
- php - $_POST 值返回空白/空
- java - 使用 XPath 选择 XSD 文件中的元素总是返回一个空列表
- angular - 防病毒软件不允许运行使用 angular 10+ 和电子创建的已安装应用程序
- c# - 具有动态分组依据的 LINQ
- wso2 - WSO2 api manager 是否支持 SCIM API?
- flutter - Flutter App Build apk报错但运行正确解决
- java - Spring Boot 嵌入式 tomcat 线程池配置
- python - 无法使用 Python 3.6 或更高版本安装 zc.buildout 和 zc.recipe.egg
- java - how can i get QQMail Starred folder with java mail
- php - PHP将视频流发送到自定义格式默认html5视频播放器