JavaScript insertAdjacentHTML和beforeend

In case you didn't know:  the damn DOM is slow.  As we make our websites more dynamic and AJAX-based, we need to find ways of manipulating the DOM with as little impact on performance as possible.  A while back I mentioned DocumentFragments, a clever way of collecting child elements under a "pseudo-element" so that you could mass-inject them into a parent.  Another great element method is insertAdjacentHTML:  a way to inject HTML into an element without affecting any elements within the parent.

如果您不知道:该死的DOM很慢。 随着我们使网站变得更加动态和基于AJAX,我们需要找到操作DOM的方法,并且对性能的影响应尽可能小。 不久前,我提到了DocumentFragments ,这是一种在“伪元素”下收集子元素的聪明方法,这样您就可以将它们大量注入到父元素中。 另一个很棒的元素方法是insertAdjacentHTML :一种将HTML注入到元素中而不影响父级元素的方法。

JavaScript (The JavaScript)

If you have a chunk of HTML in string format, returned from an AJAX request (for example), the common way of adding those elements to a parent is via innerHTML:

如果您有大量的字符串格式HTML,例如从AJAX请求返回的,则将这些元素添加到父元素的常用方法是通过innerHTML:


function onSuccess(newHtml) {
	parentNode.innerHTML += newHtml;	
}


The problem with the above is that any references to child elements or events connected to them are destroyed due to setting the innerHTML, even if you're only appending more HTML -- insertAdjacentHTML and beforeend fixes that issue:

上面的问题是,由于设置了innerHTML,对子元素或与其相关的事件的任何引用都被破坏了,即使您仅附加了更多HTML- insertAdjacentHTML并修复了该问题的endend:


function onSuccess(newHtml) {
	parentList.insertAdjacentHTML('beforeend', newHtml);
}


With the code sample above, the string of HTML is appended to the parent without affecting other elements under the same parent.  It's an ingenious way of injecting HTML into a parent node without the dance of appending HTML or temporarily creating a parent node and placing the child HTML within it.

使用上面的代码示例,HTML字符串被附加到父级, 而不会影响同一父级下的其他元素。 这是一种将HTML注入父节点的巧妙方法,而无需附加HTML或临时创建父节点并将子HTML放入其中的操作。

This API wreaks of knowing a problem exists and fixing it -- who would have thought?!  OK, that was a bit passive aggressive but you know what I mean.  Keep insertAdjacentHTML handy -- it's a very lesser known API that more of us should be using!

该API难以理解并解决了问题-谁会想到的呢? 好吧,这有点被动进取,但您知道我的意思。 请insertAdjacentHTML -这是一个鲜为人知的API,应该让更多人使用!

翻译自: https://davidwalsh.name/insertadjacenthtml-beforeend

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值