Why does IE give unexpected errors when setting innerHTML

后端 未结 10 2743
面向向阳花
面向向阳花 2020-12-10 17:20

I tried to set innerHTML on an element in firefox and it worked fine, tried it in IE and got unexpected errors with no obvious reason why.

For example if you try and

10条回答
  •  [愿得一人]
    2020-12-10 18:09

    You can modify the behavior. Here is some code that prevents garbage collection of otherwise-referenced elements in IE:

    if (/(msie|trident)/i.test(navigator.userAgent)) {
     var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
     var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
     Object.defineProperty(HTMLElement.prototype, "innerHTML", {
      get: function () {return innerhtml_get.call (this)},
      set: function(new_html) {
       var childNodes = this.childNodes
       for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
        this.removeChild (childNodes[0])
       }
       innerhtml_set.call (this, new_html)
      }
     })
    }
    
    var mydiv = document.createElement ('div')
    mydiv.innerHTML = "test"
    document.body.appendChild (mydiv)
    
    document.body.innerHTML = ""
    console.log (mydiv.innerHTML)
    

    http://jsfiddle.net/DLLbc/9/

提交回复
热议问题