gpt4 book ai didi

javascript - 在运行时添加 Knockout 模板会清空 HTML DOM

转载 作者:行者123 更新时间:2023-12-03 10:30:15 25 4
gpt4 key购买 nike

在运行时添加 knockout 模板会清空 HTML DOM

    var templateEngine = new ko.nativeTemplateEngine();
templateEngine.addTemplate = function (templateName, templateMarkup) {
document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
};
templateEngine.addTemplate("gridTable","<table></table");

所有之前的内容都会消失,DOM 会变成

<html><head><script type="text/html" id="gridView"><table></table></script></head></html>

最佳答案

正如@nemsev所说,

eveloper.mozilla.org/en-US/docs/Web/API/Document/write: calling document.write on a closed (loaded) document automatically calls document.open which will clear the document

所以,我将代码修改为,

    var templateEngine = new ko.nativeTemplateEngine();

templateEngine.addTemplate = function (templateName, templateMarkup) {
//document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
var scriptTag = document.createElement("script");
scriptTag.type = "text/html";
scriptTag.id = templateName;
scriptTag.innerHTML = templateMarkup;
var node = document.getElementsByTagName("head")[0];
node.appendChild(scriptTag);
};

templateEngine.addTemplate("gridTable","<table></table");

关于javascript - 在运行时添加 Knockout 模板会清空 HTML DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29249913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com