我在使用DWR時,試了很多次都無法在動态生成的table中的一個或多個td中進行動态連結,後來才發現原來在cellfuncs中覆寫了我想定義的輸出,不過無意中讓我發現了可以用下面的方法來處理 ( http://www.yumt.com/aeonsun )。
方法如下:
DWRUtil.addRows(id, array, cellfuncs, [options]);
這個函數估計調用的人很多,而且現在支援直接将對象傳給這個函數,這就友善了許多(以前隻能是數組),而且cellfuncs的功能也很強大,一般都會省略options參數(這個參數隻用做定義CSS或其它特殊使用,我這裡就是在這個參數裡做動态連結的處理)。
下面就是處理代碼:
DWRUtil.addRows('testid', myObject, [
function(data) { return data.name; },
function(data) {
//return data.id;
//通常都會在這裡直接傳回處理的資料,如果要實作動态多連結,
//那麼這裡就什麼都别輸出(當然也可以輸出,但這裡所有的html标記都會直接顯示在頁面上,
//無法進行解析)
//doNothing
}],
{rowCreator:function(options) {
return document.createElement("tr");
},
cellCreator:function(options) {
if(options.cellNum==1){
var td = document.createElement("td");
td.setAttribute("align","center");
var thtml = "<a href='#' οnclick=/"javascript:mydel(
'"+options.rowData.testId+"');/">删除</a>";
td.innerHTML = thtml;
return td;
}else{
return document.createElement("td");
}
}
});
cellfuncs中的處理相當重要,當直接傳回值時,會影響[options]參數中的處理内容(比如options中要
加入的TD内容會無效,當然,td.setAttribute("align","center")等是有效的)。
對DWRUtil.addRows(id, array, cellfuncs, [options])的補充:
其中:
id是table元素的id,最好使用tbody
array資料,從1.1開始支援對象
cellfuncs: 函數數組,從傳遞過來的行資料中提取單元格資料。
如:
var cellfuncs = [
function(data) { return data; },
function(data) { return data.toUpperCase(); },
function(data) {
var input = document.createElement("input");
input.setAttribute("type", "button");
input.setAttribute("value", "DOM Test");
input.setAttribute("onclick", "alert('" + data + "');");
return input;
},
function(data) { return "<input type='button' value='innerHTML Test'
οnclick='alert(/"" + data + "/");'>"; }
]
注意:這裡定義的數組size表示td的數量,面data就是array的引用,如果使用convert轉換過bean,那麼可以直接調用屬性。
[options]:這個最為有用,也是這裡所要說的重點,包含兩個對象
rowCreator: 一個用來建立行的函數(例如,你希望個tr加個css). 預設是傳回一個document.createElement("tr")
cellCreator: 一個用來建立單元格的函數(例如,用th代替 td). 預設傳回一個document.createElement("td")
一般都用不到這個參數,但對于有特殊要求的朋友來說,這就成了重點
定義的例子如下:
var custoptions = {rowCreator:function(options) {
return document.createElement("tr");
},
cellCreator:function(options) {
if(options.cellNum==1){
var td = document.createElement("td");
td.setAttribute("align","center");
var thtml = "<a href='#' οnclick=/"javascript:mydel
('"+options.rowData.testId+"');/">删除</a>";
td.innerHTML = thtml;
return td;
}else{
return document.createElement("td");
}
}
}
其中 options 參數的屬性可用的為:
rowData: the element value from the array (the same for all cells in a row)
rowIndex: the key (if map) or index (if array) from the collection
rowNum: The row number counting from 0 in this section (so if you are using tbody, it counts rows in the tbody and not the whole table)
data: The 'computed' data value for the cell (cellCreators only)
cellNum: The cell number that we are altering counting from 0 (cellCreators only)
我在上面用到了rowNum、rowData屬性
最後還是說一句,DWR太偉大了,讓我這個不懂JS的人也可以輕松上陣。