JS标签模板HTML渲染实例页面

回到相关文章 »

效果:

代码:

HTML代码:
<div id="app"></div>
                
JS代码:
const render = function (data, container) {
    container.innerHTML = '';
    container.append(element(data));
};
const html = function (arr, ...keys) {
    let result = [arr[0]];
    keys.forEach(function(key, i) {
      if (typeof key == 'function') {
        result.push(i, arr[i + 1]);
      } else {
        result.push(key, arr[i + 1]);
      }      
    });
    // 创建 template 元素
    let template = document.createElement('template');
    template.innerHTML = result.join('');
    // 遍历与事件添加
    template.content.querySelectorAll('*').forEach(node => {
        let attrs = node.attributes;
        for (let i = attrs.length - 1; i >= 0; i--) {
            let attr = attrs[i].name;
            let value = attrs[i].value;
            if (/^on[a-z]+$/i.test(attr) && !isNaN(parseFloat(value))) {           
                node.removeAttribute(attr);
                node.addEventListener(attr.replace(/^on/, ''), keys[Number(value)]);
            }
        }
    });

    return template.content;
};

let todos = ['吃饭', '睡觉', '打豆豆'];

function addTodo () {
    if (task.value.trim()) {
        todos.push(task.value);
        render(todos, app);
    }    
};

let element = function (todos) {
    return html`<h3>任务列表(${todos.length})</h3>
        <ul>
        ${todos.map(
            todo => `<li>${todo}</li>`
        ).join('')}
        </ul>
        <form onSubmit="${e => { e.preventDefault(); }}">
            <input id="task" required>
            <button onClick=${() => addTodo()}>添加任务列表</button>
        </form>
    `;
};
    
render(todos, app);