Why is it suggested to avoid [removed]?

后端 未结 1 1185
名媛妹妹
名媛妹妹 2020-12-02 00:19

Sorry for being a JavaScript noob, but can anyone please explain why is it recommended not to use .innerHTML. When we have something that is faster and easier i

相关标签:
1条回答
  • 2020-12-02 00:47

    innerHTML is a sledgehammer. It will blast away the contents of the selected DOM element and replace them with whatever happens to be assigned at the time. This leads to a number of HTML escaping and validation issues.

    More importantly, for pages where a large number of events are bound, using innerHTML to append another element will regenerate DOM elements, which means event bindings can get lost.

    There are also some issues regarding memory leaks in older versions of IE when elements are removed from the DOM.


    With all of that said, I'm not telling you that you shouldn't be using innerHTML. I use it all the time in jQuery when I use $(selector).html(). Sometimes a sledgehammer is the right tool for the job, and when events are delegated properly it won't matter how much the content is reloaded.

    0 讨论(0)
提交回复
热议问题