在运行时添加 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/