克隆HTML元素与使用Javascript创建它
我通过ajax请求得到一份员工名单。然后,我创建了一组带有姓名地址电话等的div。这些新元素还有一些提供功能的按钮。我一直在使用这种方法:克隆HTML元素与使用Javascript创建它,javascript,html,Javascript,Html,我通过ajax请求得到一份员工名单。然后,我创建了一组带有姓名地址电话等的div。这些新元素还有一些提供功能的按钮。我一直在使用这种方法: var Employee = function(params) { this.name = params.name; this.hrid = params.hrid; this.initialize = function() { this.container = document.createElement('div'); th
var Employee = function(params) {
this.name = params.name;
this.hrid = params.hrid;
this.initialize = function() {
this.container = document.createElement('div');
this.contName = document.createElement('div');
this.contHRID = document.createElement('div');
this.myButton = document.createElement('button');
this.contName.innerHTML = this.name;
this.contHRID.innerHTML = this.hrid;
this.container.appendChild(this.contName);
this.container.appendChild(this.contHRID);
this.container.appendChild(this.myButton);
this.addObservers();
}
this.addObservers = function() {
this.myButton.observer = this.dostuff.bind(this);
this.myButton.addEventListener('click', this.myButton.observer);
}
this.dostuff = function() {
// do stuff
}
}
这种方法对我来说效果很好,但我想知道,如果在某个地方用已经构建的HTML创建一个隐藏的div并克隆它,是否会更好
我很想听听关于哪种方法更好,或者是一种六合一的情况的想法。cloneNode比createElement快。首先,我将创建一个div并克隆下一个div,而不是在一行中创建它们。对于隐藏的HTML div与createElement,这取决于具体情况。如果您需要克隆它一次,那么无论哪种方式都是类似的。如果它必须被克隆几次,那么使用隐藏div可能会更好。我自己也使用了类似的方法。我创建了一个包含子节点的隐藏div,并根据情况使用JS填充innerHTML/textContent,但在这种情况下,一次只能看到一个div。该网站表示相反,createElement跨浏览器的速度更快