document.createElement not working

前端 未结 5 1808
南方客
南方客 2021-01-16 06:20

I am creating a plugin using jQuery library.

Here i am storing String.prototype in a variable then i am using this variable to extend my Sting objec

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-16 07:04

    You are getting a reference to a function that is a member of the document. When you call that reference directly, it's context is now the window rather than the document. Here's an example:

    http://jsfiddle.net/DeCNx/

    var foo = {
      createElement: function(tagname) {
        if (this._secretvarthatisneeded) {
          console.log(tagname + " Element Created!");
        }
      },
      _secretvarthatisneeded: true
    }
    
    foo.createElement("FOOBAR"); // works
    
    var bar = foo.createElement;
    bar("BARFOO"); // doesn't work
    bar.call(foo,"BARBAR") // works
    

    Since the context was lost, the bar() call didn't result in a console.log();

    obviously this is just a simplification to demonstrate.

    Update: For the use you are making, i'd suggest doing this:

    $.createElement = function(tagName,attributes){
        return $(
            document.createElement(tagName),
            attributes ? attributes : {}
        )
    }
    

    Now you can simply do $.createElement("button").html("tag").appendTo("#myDiv"); It is fast and still easy to read. Note however IE has problems with inputs, if you're creating input elements, i suggest using $("") rather than this.

提交回复
热议问题