如何在JavaScript中插入一个随机对象字面值到DOM? [英] How to insert a random object literal to the DOM in JavaScript?
问题描述
我正在为内部包含DOM节点的表单输入字段制作自定义类包装,并增加了额外的功能方法。
I am making custom class wrappers for form input fields that internally contain a DOM Node and are augmented with extra functionality method.
我的问题是如果与.toString()类似的方法附加到DOM,因为我想直接将我的对象插入到DOM中,而不是调用其他方法
My questions is if there is a similar method to .toString() for appending to the DOM as I would like to directly insert my objects to the DOM instead of calling additional methods
在其他工作中,以下是我所拥有的示例:
In other workds, here is an example of what I have:
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;
}
}
所以我可以使用它如下: p>
so that i can use it as follows:
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继承,因为它不是公共类
You can't simply inherit from the DOM Node as it is not a public class
我已经尝试了其他问题,但似乎没有答案...任何想法将受到高度的欢迎
I've tried looking at other questions but none seem to have the answer... any ideas would be highly welcomed
推荐答案
你不能继承自己的DOM构造函数,但是你可以从jQuery继承你的包装类。
You can't inherit from the native DOM constructors, but you can inherit your wrapper class from 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。身体).append(new A)
或 new A()。appendTo(document.body)
等。
With that, you could just $(document.body).append(new A)
or new A().appendTo(document.body)
etc.
这篇关于如何在JavaScript中插入一个随机对象字面值到DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!