12

很抱歉成为 JavaScript 菜鸟,但谁能解释一下为什么不建议使用.innerHTML. 当我们有某种形式上更快、更容易的东西时,我们.innerHTML为什么不使用它呢?

4

1 回答 1

14

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.

于 2013-08-29T04:36:39.337 回答