dom模式中的新建element元素一般是通过document.createElement方法来获得,但是我发现还有一个特殊的地方。
var img=new Image();
img.src="http://xxxxxx";
document.lastChild.lastChild.appendChild(img);
以上代码是通过new新建对象的方法来得到特殊element,于是我想能不能自己建立一个类似的类,然后通过new操作来得到相应的element元素,以下是代码
var Anchor=function(){};//新建锚链接类
Anchor.prototype=document.createElement("a");
var a=new Anchor();
a.innerText="123";
a.href="http://xxxxx";
document.lastChild.lastChild.appendChild(a);//Error!!!
新建出来的对象a是element的类型,可就是不能通过appendChild方法来添加到页面,提示参数类型错误。我希望通过类似new Anchor()之类的方法来构建一个锚链接对象,然后通过appendChild来把他加入document,最后显示在浏览器中,我的代码到底哪里出了问题,或各位大大们有什么高招,请指教!!

解决方案 »

  1.   


    <script>
    var Anchor = function(){
    return document.createElement("a");
    };//新建锚链接类window.onload=function(){
      var a=new Anchor();
      a.innerHTML="123";
      a.href="http://xxxxx";
      document.getElementById("xx").appendChild(a);
    }
    </script><div id="xx"></div>
      

  2.   

    哈哈谢谢了,朋友,但是为什么给Anchor的原型返回Element元素会没有用呢,按道理说这样也可以呀。
      

  3.   

    比方说我想用下面的形式来实现Anchor类的实例化。
    var a=new Anchor("123","http://xxxxxxxxx");
    document.lastChild.lastChild.appendChild(a);
    就是自定义Anchor的构造函数。
      

  4.   

     function anchor(text, uri, className)
            {
                this._hyperlink = document.createElement("a");
                this._hyperlink.innerHTML = text;
                this._hyperlink.href = uri;
                this._hyperlink.className = className;
            }        anchor.prototype.append = function(containerNode)
            {
                containerNode.appendChild(this._hyperlink);
            }        window.onload = function()
            {
                var oelement = new anchor("sohu.com", "http://www.sohu.com", "");
                oelement.append(document.body);
            }
      

  5.   

    看来好像是只能这样了,谢谢五楼的兄弟,不过还是不太完美,希望能把document.createElement的返回值让Anchor继承,并且可以自定义Anchor的构造函数,最后用new Anchor(a.b)来实例,并且可以用appendChild来加入document tree。