目的:用JS擷取滑鼠點選表格某行資料,然後在JSP中将資料傳到servlet進行處理
網上有人說用AJAX可以簡單實作,但小弟還沒接觸AJAX,就隻有自已想辦法用JS處理。
方法:設定一個隐藏域,在JS裡放一個方法監控滑鼠對表格的點選操作并将資料傳給隐藏域。在JSP中設定FORM送出隐藏域給背景SERVLET
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
function clickRow(row){
//點選行變色處理
if(row.style.backgroundColor == ""){
var tbSource = $("tbSource");
for(var i=0; i<tbSource.rows.length; i++){
tbSource.rows[i].style.backgroundColor = "";
}
row.style.backgroundColor = "#dddddd";
}else{
row.style.backgroundColor = "";
}
document.getElementById('row').value=row.cells[1].innerText;//将所點選行資料傳給隐藏域
}
function postRow(){
document.deleteAdmin.submit();
}
window.onload = function(){
var tbSource = $("tbSource");
for(var i=0; i<tbSource.rows.length; i++){
tbSource.rows[i].onclick = function(){
clickRow(this);
}
}
};
</script>
JSP表單:
<table width="100%" cellpadding="0" cellspacing="0" id="tbSource">
<tr>
<td height=20 ><form name="deleteAdmin" method="post" action="addAdmin">
<input type="hidden" name="row" >
<input type="hidden" name="action" value="delete" ></form></td>
<a href="#" target="_blank" rel="external nofollow" οnclick="postRow()">删除</a></td>
</tr>
</table>