最近用做的公司內部管理系統的工時管理,需求是要在table中隨意添加、刪除工作項,前臺全部用js控制table ,所以用到了table中常用 的集中方法。
(1)得到table 中tbody 的內容 :$('#simple-table').find('tbody').html();
(2)點擊td時,獲取點擊的行號:
$('#simple-table tbody').on( 'click', 'td', function (e) {
normalRowIndex = $(this).parent().index(); //行號console.log("正常工作表行:"+normalRowIndex);
});
(3)爲table追加一行:
function addNormalTR(){
$('#simple-table').find('tbody').append(trtd); //tdtd爲拼接的trtd 的html內容。
}
(4) 點擊td中的元素獲取,當前行號: obj.parentNode.parentNode.rowIndex;//obj 爲元素對象
(5)點擊table中td下的一個按鈕刪除當前行:
function delNormalTR(obj){//obj爲點擊的元素,傳this過來就ok
//alert("點擊的td的:"+obj.parentNode.parentNode.rowIndex);
//alert("當前行號"+normalRowIndex);
var rowIndex = obj.parentNode.parentNode.rowIndex;
if(rowIndex !=1 ){
$('#simple-table tr:eq(' + rowIndex + ')').remove();
}
}
(6) 獲取table 中各個對象的方法
var trNode = $(this).parent().parent(); //獲取input的“爺爺”--tr
var forthChildTdNode = trNode.children().eq(3);//獲取第四個td
var firstInput = forthChildTdNode.children(); //獲取第一個input
(7)遍歷tr td
$('#simple-table tr').each(function(i){ // 遍歷 tr
var t ="";
var projectid = $('#simple-table tr:eq('+(i+1)+') td:eq(0)').children("select").val();
// alert(projectid);
$(this).children('td').each(function(j){ // 遍歷 tr 的各個 td
// alert("第"+(i+1)+"行,第"+(j+1)+"個td的值:"+$(this).text()+"。");
var temp = $(this).children().val();
var temp1 =temp;
if(temp != null && temp !=""){
temp = temp+"##,";
t += temp ;
}
if(j == 2){
normalTimeCount += (temp1*1);
//alert("projectid="+projectid);
// alert("temp1="+temp1);
//typeof(tmp) == "undefined"
if(typeof(temp1) != "undefined" && (temp1=='' || temp1 == null || temp1==0)){
swal({
title: "提示",
text: "工時不能爲空或0",
type: "info"});
$("#btnSave").button('reset');
throw SyntaxError('工時不能爲空或0');
}
}
});
normalTime +=t+"##;";
console.log("normalTime="+normalTime);
});