首页 > 解决方案 > 更改后在 html 中设置模板

问题描述

我有一个下一个方法,如何在 DOM 中编译和设置我的 html:

export function initHTMLOperator(container) {
    if (container.template) {
        const template =  SF.handlebars.compile(container.template);
        const html = template(container);
        const elem = document.getElementsByTagName(container.id)[0];
        elem.innerHTML = html; // set compiled template
    }
}

container.template有一个模板
container- 它是带有模板变量的对象。

编译后我在 DOM 中设置了 html。

但是我在更改输入时遇到问题,我重新编译模板并失去焦点。

是否可以在没有 innerHTML 的情况下更新 DOM 中的模板?我的意思是更新模板但没有设置完整的 html,只有更改。

标签: handlebars.js

解决方案


你想要的是像反应而不是把手那样的东西,你应该使用虚拟 DOM 并只应用更改,但把手不提供这样的功能。所以不,如果你想要你的新模板,那么你必须用类似 innerHTML 的东西替换整个内容。但是,如果唯一的问题是失去焦点,您可以在替换内容之前保存它,并在替换模板后重置焦点。


推荐阅读