为什么建议避免使用.innerHTML? [英] Why is it suggested to avoid .innerHTML?

查看:155
本文介绍了为什么建议避免使用.innerHTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉成为JavaScript菜鸟,但任何人都可以解释为什么建议不要使用 .innerHTML 。当我们以 .innerHTML 的形式更快更轻松时,为什么我们不应该使用它?

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 in form of .innerHTML , why shouldn't we use it ?

推荐答案

innerHTML 是一把大锤。它将爆炸所选DOM元素的内容,并用当时分配的任何内容替换它们。这导致了许多HTML转义和验证问题。

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.

更重要的是,对于绑定了大量事件的页面,使用 innerHTML 附加另一个元素会重新生成DOM元素,这意味着事件绑定可能会丢失。

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.

在旧版本的内存泄漏方面也存在一些问题IE从元素中删除元素时。

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

所有这些都说明了,我不是说你不应该不要使用 innerHTML 。当我使用 $(选择器).html()时,我一直在jQuery中使用它。有时大锤是工作的正确工具,当事件被正确委派时,重新加载内容无关紧要。

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.

这篇关于为什么建议避免使用.innerHTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆