javascript將table的td變為可編輯的input,實現表格動態編輯

來源:互聯網
上載者:User

  很多情境都會遇到再網頁上,使用者喜歡像用excel一樣,直接對html的table內容進行操作,所以寫了個方便使用的外掛程式

  csdn下載地址 :http://download.csdn.net/detail/w172087242/9589681

  升級版下載地址


下面是javascript代碼:

  

/***  *  功能:將唯讀表格變成可編輯表格  *  支援自訂事件進行編輯  *  表格樣式可以自己設定  *  只負責tbody部分  *  data結構樣式如下:     {rows:3, data:[{name:"littlehow", age:18},{...}], column:["name", "age"]}  *  @author littlehow  *  @time 2016/7/29 星期五  **/(function() {var $ = function(node) {return typeof node == "string" ? document.getElementById(node) : node;}var $1 = function(node, parent){var nd = document.createElement(node);if(parent) parent.appendChild(nd);return nd;}/** 綁定事件流 */var bind = function(obj, eventName, funcionName){if(obj.addEventListener){obj.addEventListener(eventName, funcionName,false); }else if(obj.attachEvent) {obj.attachEvent("on" + eventName, funcionName); }else{obj["on" + eventName] = funcionName; }};var fulltable = function(tbody, data){var pd = data.data;var column = data.column;for(var i=0, len=data.rows; i<len; i++){var tr = $1("tr", tbody);var cd = pd[i];for(var j=0,jlen=column.length; j<jlen; j++){var td = $1("td", tr);td.innerHTML = cd[column[j]];//innerText不相容Firefox,可以自己寫innerText和textContent的相容,這裡就直接用innerHTML了}}}var littlehow_edit_table = function(tbody, ev){this.tbody = $(tbody);this.event = ev ? ev : "click";//預設為單機事件this.init = function(data) {//data可以是undefinedif(data) {fulltable(this.tbody, data);}//調用可編輯this.edit();}this.edit = function(){var tds = this.tbody.getElementsByTagName("td");for(var i=0,len=tds.length; i<len; i++){bind(tds[i], this.event, this.click);}}this.click = function(){//alert(this.children.length);if(this.children.length > 0) return;var v = this.innerHTML;this.innerHTML = "";var input = $1("input", this);input.type = "text";input.value = v;input.focus();//游標聚集bind(input, "blur", blur);}var blur = function(){var v = this.value;this.parentNode.innerHTML = v;}}window.$$ = function(id, ev){return new littlehow_edit_table(id, ev);};})()

如果想要調用,可以去下載頻道下載。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.