2010-01-04 31 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。
明確的切入使前端開發成爲一種快樂建立和維護。