2010-01-04 33 views
1

考虑使用JavaScript函数向页面添加HTML元素。在该函数中,需要指定HTML元素的行。但是,如果这个HTML很复杂,那么它可能会让你的代码看起来丑陋难调。请看下面的例子(玩注意ul.innerHTML等):在Javascript函数中组织HTML内容

function addHTMLField(area,limit) { 
     var field_area = document.getElementById(area); 
     var all_inputs = field_area.getElementsByTagName("ul"); 
     var last_item = all_inputs.length - 1; 
     var last = all_inputs[last_item].id; 
     var count = Number(last.split("_")[1]) + 1; 
     if(count > limit && limit > 0) return; 
     if(document.createElement) { //WC3 Dom method 
      var ul = document.createElement("ul"); 
      ul.innerHTML = "<ul style='margin-top: 10px' id='blog_"+count+"'><li>Blogname:<br/> <input type='text' name='blog["+count+"][name]' size='40' /></li><li>Blog Title:<br/> <input type='text' name='blog["+count+"][title]' id='blogtext_"+count+"' size='40' /></li><li>Username:<br/> <input type='text' name='blog["+count+"][username]' id='blogcategory_"+count+"' size='40' /></li><li>E-Mail:<br/> <input type='text' name='blog["+count+"][email]' id='blogcategory_"+count+"' size='40' /> <br/><small>A new user will be created if the above email address is not in the database. <br/>The username and password will be mailed to this email address. </small></li><li><input type='button' value='Remove Blog' onclick=\"removeItem('blog_"+count+"')\"> </li></ul>"; 
      field_area.appendChild(ul);      
     } else { 
      alert('an error occurred in the addLinkField function'); 
     } 
    } 

是否有比这更好的方式来组织内部的Javascript功能HTML?请注意,由于某些字段是动态填充的,因此我无法将所有HTML都放在Javascript外部。

感谢您的任何见解。

+2

为什么不为所有的子节点使用document.createElement而不是设置ul.innerHTML? – vit 2010-01-04 11:43:26

回答

3

我认为分离代码和HTML是非常重要的。在JavaScript中编辑HTML是一种可怕的磨难。有一些解决方案可以很好地处理动态变量。

有使用Javascript模板引擎像这样的:PURE

约翰Resig的(JQuery的的作者)也放在一起a micro-templating engine。这些例子展示了一个很好的方式,使用从隐藏div 获取的HTML代码,该页面位于页面内,我找到了一个近乎完美的解决方案:这种方式HTML是它所属的位置,但可以由您动态填充。我不是JQuery迷,但我倾向于盲目地相信,如果像Resig这样的人建立它,它也是o.k.从性能角度来使用。

+0

感谢Pekka的链接:) – Mic 2010-01-04 12:20:03

+0

不客气,你的引擎看起来非常好! – 2010-01-04 13:12:17

2

我是XML的XSLT的大风扇在浏览器中运行,分离以及JS和HTML。

但后来我们转向JSON1年以前,PURE是我们的一个类似的偏离损失响应。

我们正在建立一个Web应用程序(即将测试版)完全基于纯的HTML。
明确的切入使前端开发成为一种快乐建立和维护。