我想在使用 javascript 的 document.createElement() 创建的元素上创建 jQuery 类型链接。每当我尝试在由我的函数定义的父对象上运行“append”方法时,以下代码都会生成错误“无法调用未定义的方法“appendChild””。如有任何帮助或建议,我们将不胜感激。
this.el = (function () {
function _el() {
var self = this,
ele;
this.add = function (tag) {
ele = document.createElement(tag);
return this;
},
this.byId = function (id) {
ele = document.getElementById(id);
return this;
},
this.byClass = function (cl) {
ele = document.getElementsByClassName(cl);
return this;
},
this.id = function (name) {
ele.id = name;
return this;
},
this.cl = function (name) {
ele.className = name;
return this;
},
this.css = function (style) {
_this.setCSS(ele, style);
return this;
},
this.html = function (str) {
ele.innerHTML = str;
return this;
},
this.append = function (parent) {
if (parent.nodeType === 1) {
parent.appendChild(ele);
}
console.log(ele);
console.log(ele.nodeType);
return this;
};
return this;
}
return new _el();
}());
这就是我在代码中使用该函数的方式。第一次使用有效,而第二次则无效。它与我的函数返回的对象类型有关,但我不知道如何纠正。
var dialog = hlp.el.add("div").cl("alphaDialog").append(document.body);
var top = hlp.el.add("div").append(dialog);
最佳答案
this.append 函数返回 this
对象,其中包含 _ele
js 对象。我们必须返回 HTML 元素 ele
。在 this.append
中,我们返回 ele
;
this.el = (function () {
function _el() {
var self = this,
ele;
this.add = function (tag) {
ele = document.createElement(tag);
return this;
},
this.byId = function (id) {
ele = document.getElementById(id);
return this;
},
this.byClass = function (cl) {
ele = document.getElementsByClassName(cl);
return this;
},
this.id = function (name) {
ele.id = name;
return this;
},
this.cl = function (name) {
ele.className = name;
return this;
},
this.css = function (style) {
_this.setCSS(ele, style);
return this;
},
this.html = function (str) {
ele.innerHTML = str;
return this;
},
this.append = function (parent) {
if (parent.nodeType === 1) {
parent.appendChild(ele);
}
console.log(ele);
console.log(ele.nodeType);
//return this; // this holds javascript object, not element
return ele; // return our ele variable which holds the element
// this.append() is the end of the chain
};
return this;
}
return new _el();
}());
关于javascript - 如何在 javascript document.createElement 上应用链接方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35027010/