weixin_33701294 2013-04-06 19:04 采纳率: 0%
浏览 15

动态创建元素

I'm currently working on several Apps that include AJAX calls and I'm using JSON format to retrieve data from the server. Each page needs to create content based on the JSON response, and I'm currently creating the content like:

function createBox1(json) {
   var bigbox = document.createElement('div');
   bigbox.className = 'class1';

   var firstbox = document.createElement('div');
   firstbox.className = 'first-box';

      var firstNestedBox = document.createElement('div');
      var secondNestedBox = document.createElement('div');
      var thirdNestedBox = document.createElement('div');
   var secondbox = document.createElement('div');
...

So basically its kinda a long code and I wanted to know if there is a better way to do it.

PS: I have seen some libraries where they do something like:

function o(t,e){var i=document.createElement(t||"div"),o;for(o in e)i[o]=e[o];return i}

and I suppose that's how they create multiple div elements, but I'm not sure how does that works.

Thanks in Advance (:

  • 写回答

1条回答 默认 最新

  • 北城已荒凉 2013-04-06 19:11
    关注

    There's nothing wrong with the way you're doing it, but it's faster to just clone an empty div instead of creating new ones, and it's faster to use a fragment when building markup, and then insert the fragment in the DOM once everything is built instead of inserting each element in the DOM etc.

    Just for making shorter code, a function could be used, but it's really just an uneccessary function call:

    function createBox1(json) {
       var div             = document.createElement('div'),
           bigbox          = div.cloneNode(false),
           firstbox        = div.cloneNode(false),
           firstNestedBox  = div.cloneNode(false),
           secondNestedBox = div.cloneNode(false),
           thirdNestedBox  = div.cloneNode(false),
           secondbox       = div.cloneNode(false):
    
       bigbox.className = 'class1';
       firstbox.className = 'first-box';
    
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置