很多情境都會遇到再網頁上,使用者喜歡像用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);};})()
如果想要調用,可以去下載頻道下載。