Skip to content

Instantly share code, notes, and snippets.

@xuexb
Created August 8, 2016 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuexb/37919b6939e1e32ad67537d9b9362532 to your computer and use it in GitHub Desktop.
Save xuexb/37919b6939e1e32ad67537d9b9362532 to your computer and use it in GitHub Desktop.
js数据拼接html的另类方法
var data = [
    {
        id: 1,
        title: '标题1',
        content: '内容1'
    },
    {
        id: 2,
        title: '标题2',
        content: '内容2'
    },
    {
        id: 3,
        title: '标题3',
        content: '内容3'
    }
];

// data->html

var listHtml = data.filter(function (val) {
    return val.id > 1;
}).map(function (val) {
    return [
        '<li>',
            '<h3>' + val.title + '</h3>',
            '<p>' + val.content + '</p>',
        '</li>'            
    ].join('');
}).join('');

var html = [
    '<h2>我是标题</h2>',
    '<ul>',
        listHtml,
    '</ul>'
].join('');

console.log(html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment