我正在为表单输入字段制作自定义类包装器,这些字段内部包含 DOM 节点,并通过额外的功能方法进行增强。
我的问题是是否有与 .toString() 类似的方法用于附加到 DOM,因为我想直接将对象插入到 DOM 而不是调用其他方法
换句话说,这是我所拥有的一个示例:
function A () {
this.element = documenet.createElement('input');
// blah blah logic
this.toString = function () {
return '<input type="'+this.element.type+'" value="'+this.element.value+'" />';
}
// a similar method to this i'ld like
this.toString = function () {
return this.element;
}
}
这样我就可以按如下方式使用它:
var a = new A();
// this works as it calls .toString(), but it is a hack and it is not pretty
document.body.innerHTML += a;
// this is what i'd want to be able to do:
document.body.appendChild(a);
// this is what **I AM REALLY TRYING TO AVOID:**
document.body.appendCHild(a.toElement());
你不能简单地继承 DOM Node,因为它不是一个公共类
我尝试过查看其他问题,但似乎没有一个有答案......任何想法都会受到高度欢迎
您不能从本机 DOM 构造函数继承,但可以从 jQuery 继承包装类!
function A () {
if (!(this instanceof A)) return new A(); // fix wrong constructor invocations
if (this.length) { // shouldn't be set yet, so another odd invocation:
var empty = Object.create(A.prototype); // a new, but *empty* instance
empty.length = 0; // explicitly set length
return empty;
}
this[0] = document.createElement('input');
…
// or you might want to call $.fn.init
this.context = undefined; // not sure whether
this.selector = ""; // we need those two lines
this.length = 1; // but the length is obligatory
}
A.prototype = Object.create($.fn, {constructor:{value:A,configurable:true}});
A.prototype.toString = function () {
return '<input type="'+this[0].type+'" value="'+this[0].value+'" />';
}
有了这个,你就可以$(document.body).append(new A)
or new A().appendTo(document.body)
etc.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)