在table中插入多行,能使用與insertAdjacentHTML相似的功能嗎?_javascript技巧

來源:互聯網
上載者:User
對於div等元素來說,插入一段html是很容易的事情,但是對於表格來說就太難了。一般情況下,我們都是用appendChild的方式,一行行、一格格地添加,操作起來很繁鎖。能不能拼一串字元,就能直接加入到表格中呢?

  下面的例子實現了這個功能,同樣地,該例支援IE和firefox。該功能的實現意義重大,這樣頁面元素的處理,就全部都能夠用拼html字串的方法來實現了。
<html> <body> <table id=tb1 border=1 width=100> <tr><td>1</td></tr> </table> <button onclick=run()>插入行</button> </body> <script> function run(){ insTable(document.getElementById("tb1"),"<tr><td>2</td></tr><tr><td>3</td></tr>") } function insTable(tb,str){ var o=document.createElement("div"),ol o.innerHTML="<table>"+str+"</table>" ol=o.childNodes[0].tBodies[0].rows while(ol.length>0){ tb.tBodies[0].appendChild(ol[0]) } } </script>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.