JavaScript:最好使用innerHTML或(很多)createElement调用来添加复杂的div结构? [英] JavaScript: Is it better to use innerHTML or (lots of) createElement calls to add a complex div structure?

查看:290
本文介绍了JavaScript:最好使用innerHTML或(很多)createElement调用来添加复杂的div结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个需要一个复杂的div块的问题,在一组〜100个元素中为每个元素创建一次。

I'm looking at a problem that needs a complex block of divs to be created once for each element in a set of ~100 elements.

每个单独的元素除了内容以外,它们是一样的(在HTML中)这样的东西:

Each individual element is identical except for the content, and they look (in HTML) something like this:

<div class="class0 class1 class3">
<div class="spacer"></div>
<div id="content">content</div>
<div class="spacer"></div>
<div id="content2">content2</div>
<div class="class4">content3</div>
<div class="spacer"></div>
<div id="footer">content3</div>
</div>

我可以:

1)创建所有元素作为 innerHTML 与字符串连接添加内容。

1) Create all the elements as innerHTML with string concatenation to add the content.

2)使用 createElement setAttribute appendChild 创建并添加每个div。

2) Use createElement, setAttribute and appendChild to create and add each div.

选项1得到一个稍小的文件下载,但是选项2似乎要稍快一些。

Option 1 gets a slightly smaller file to download, but option 2 seems to be slightly faster to render.

除了性能有没有一个很好的理由通过一条路线或另一条路线?任何跨浏览器问题/性能gremlins我应该测试?

Other than performance is there a good reason to go via one route or the other? Any cross-browser problems / performance gremlins I should test for?

...或者我应该尝试模板和克隆方法?

...or should I try the template and clone approach?

非常感谢。

推荐答案

使用像jQuery,Prototype,Dojo或mooTools这样的库,因为这两种方法都充满麻烦:

Neither. Use a library like jQuery, Prototype, Dojo or mooTools because both of these methods are fraught with trouble:

  • Did you know that innerHTML on tables for IE is readonly?
  • Did you know for the select element it's broken as well?
  • How about problems with createElement?

主要JavaScript库的作者花了很多时间,错误跟踪系统,以确保当您调用他们实际工作的DOM修改工具时。

The writers of the major javascript libraries have spent a lot of time and have entire bug tracking systems to make sure that when you call their DOM modifying tools they actually work.

如果您正在编写一个图书馆以与上述工具竞争(如果您是幸运的话),那么我会根据性能选择该方法,而innerHTML在过去一直赢了,而且innerHTML是一种本地方法,所以它是一个很安全的选择,它将保持最快。

If you're writing a library to compete with the above tools (and good luck to you if you are), then I'd choose the method based on performance, and innerHTML has always won out in the past, and since innerHTML is a native method, it's a safe bet it will remain the fastest.

这篇关于JavaScript:最好使用innerHTML或(很多)createElement调用来添加复杂的div结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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