【问题标题】:How to cast an object to a DOMElement?如何将对象转换为 DOMElement?
【发布时间】:2014-02-13 12:42:18
【问题描述】:

我想将 un 对象转换为 DOM 对象。

例如,我有这个构造函数:

function Input(type, id, name, value)
{
    this = document.createElement("input");
    ...
}

如您所见,我在正文中添加了 this = document.createElement("input"); 以尝试将 Input 对象转换为 DOMElement 对象,但它不起作用。

(我知道我可以做到this.input = document.createElement("input");,但我绝对想将唯一的this 转换为document.createElement("input");

请问你有什么想法吗?

提前谢谢你,诚挚的

【问题讨论】:

  • this 是只读的。

标签: javascript object dom casting element


【解决方案1】:

我不确定您要做什么,但您可以尝试以下方法:

<div id="container"></div>

<script type="text/javascript">

    var Input = function(type, id, name, value){
        this.element = this.create();

        this.setType(type);
        this.setValue(value);
        this.setName(name);

        return this.element;
    };

    Input.prototype.create = function(){
        return document.createElement("input");
    };

    Input.prototype.setType = function(type){
        this.element.type = type;
    };

    Input.prototype.setValue = function(value){
        this.element.value = value;
    };

    Input.prototype.setName = function(name){
        this.element.name = name;
    };

    var newInput = new Input("text", "", "qwe", "qwe");

    document.getElementById("container").appendChild(newInput);

</script>

【讨论】:

  • 非常感谢,你的代码就是我要找的!!!我在您的代码中看到我忘记了return this.element 行现在使用return this.element 行,alert(newInput);准确返回 [object HTMLInputElement],这就是我想要的。这样就解决了,再次感谢您
【解决方案2】:
猜你喜欢
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 2018-02-13
  • 2011-05-26
  • 2017-10-20
  • 2015-03-18
相关资源
最近更新 更多