我正在寻找的是一个函数或一段代码,它们可以帮助我将数组的结果转储到 HTML DIV 中。我知道有不同的方法可以这样做,但这些都需要遍历数组。我正在寻找的更像是一个映射工具。例如:
假设我的 javascript 中有以下数组:
var myarray = [];
myarray['name'] = 'value1';
myarray['lastname'] = 'value2';
myarray['address'] = 'value3';
接下来我想做的是以某种方式将数组的每个值与它们在 HTML DIV 中的等价物相关联。例如:
<div id="name"></div>
<div id="lastname"></div>
<div id="address"></div>
或者更好的是,我希望能够在我的 HTML 中有一个表格,可以在不使用 DIV 的情况下使用该信息获取该表格。像这样的东西:
<table width="277" height="146" border="1">
<tr>
<td width="97">Name</td>
<td width="87">{name}</td>
</tr>
<tr>
<td>Lastname</td>
<td>{lastname}</td>
</tr>
<tr>
<td>Address</td>
<td>{address}</td>
</tr>
</table>
所以我的想法是,当我在我的 Javascript 中获取值时(通过 jquery),我可以将数组的全部内容写入 HTML 表,而不必遍历数组的每个值。
有什么想法可以帮助我实现目标吗?
最佳答案
这是一个非常简单的模板系统。首先为您的模板创建脚本标签:
<script id="template" type="text/html">
<table width="277" height="146" border="1">
<tr>
<td width="97">Name</td>
<td width="87">{name}</td>
</tr>
<tr>
<td>Lastname</td>
<td>{lastname}</td>
</tr>
<tr>
<td>Address</td>
<td>{address}</td>
</tr>
</table>
</script>
然后您可以根据您的数据(作为对象)使用这个小函数渲染模板:
// An object, not an array
var data = {
name: 'value1',
lastname: 'value2',
address: 'value3'
};
// Very basic templating
function render(template, data) {
var patt = /\{([^}]+)\}/g; // matches {key}
return template.replace(patt, function(_, key) {
return data[key];
});
}
// Grab html from template
var template = $('#template').html();
// Generate html given the data and append to body
$('body').append(render(template, data));
演示: http://jsbin.com/ibeBIxO/1/edit
如果您想要更复杂的东西,请查看 Underscore templates .
关于javascript 将数组的元素映射到 HTML DIV 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19041216/