Как я могу применить метод сцепления на javascript document.createElement
Я хотел бы создать цепочку типов jQuery для элемента, созданного с помощью document.createElement() javascript. Следующий код генерирует ошибку "Невозможно вызвать метод appendChild of undefined" всякий раз, когда я пытаюсь запустить метод "append" для родительского объекта, который был определен моей функцией. Любая помощь или предложения приветствуются.
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);
1 ответ
Решение
Функция this.append возвращает this
объект, который содержит _ele
JS объект. Мы должны вернуть наш элемент HTML ele
, В this.append
мы return 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();
}());