以编程方式解析 html 字符串而不附加到 DOM 的最佳方法
Best approach for parsing html string Programatically without appending to DOM
我目前正在构建一个解析器和编译器来处理我自己的自定义 2 向数据绑定,一切正常,但是它涉及我通过 .innerHTML
附加我的模板字符串,这不是很有效。
解析时,我需要访问某些 DOM 方法,例如 .getElementsByTagName('*')
并执行其他遍历任务,因此我无法使用 DOC 片段,并且由于字符串是 text/html
无法使用使用 text/xml
的 DOMParser()
有谁知道一个简单的解决方案,可以让我解析我的字符串并将元素存储在存储中,然后我可以在附加到 DOM 之前操作和绑定事件?
这是我试图避免的当前 html 字符串插入的精简版本:
(function(){
'use strict';
var globalModel = function(data){
this.templateString = data.template || '';
this.template = data.node || document.body;
this.initialise();
};
globalModel.prototype = {
initialise: function(){
this.template .innerHTML = this.templateString;
this.compile();
},
compile: function(){
var nodes = this.template.getElementsByTagName('*');
//calling other methods with nodes, parsing and doing more traversal
}
}
var myModule = new globalModel({
template: '<div>Your email is {{email}} <input type="text" data-relation="email" /> {{test}} </div>'
});
})();
尝试这样做:
var temp = document.createElement('div')
temp.innerHTML = this.templateString;
那么绑定之后就可以把children全部移动到this.containerNode了
我目前正在构建一个解析器和编译器来处理我自己的自定义 2 向数据绑定,一切正常,但是它涉及我通过 .innerHTML
附加我的模板字符串,这不是很有效。
解析时,我需要访问某些 DOM 方法,例如 .getElementsByTagName('*')
并执行其他遍历任务,因此我无法使用 DOC 片段,并且由于字符串是 text/html
无法使用使用 text/xml
有谁知道一个简单的解决方案,可以让我解析我的字符串并将元素存储在存储中,然后我可以在附加到 DOM 之前操作和绑定事件?
这是我试图避免的当前 html 字符串插入的精简版本:
(function(){
'use strict';
var globalModel = function(data){
this.templateString = data.template || '';
this.template = data.node || document.body;
this.initialise();
};
globalModel.prototype = {
initialise: function(){
this.template .innerHTML = this.templateString;
this.compile();
},
compile: function(){
var nodes = this.template.getElementsByTagName('*');
//calling other methods with nodes, parsing and doing more traversal
}
}
var myModule = new globalModel({
template: '<div>Your email is {{email}} <input type="text" data-relation="email" /> {{test}} </div>'
});
})();
尝试这样做:
var temp = document.createElement('div')
temp.innerHTML = this.templateString;
那么绑定之后就可以把children全部移动到this.containerNode了