2013-03-06 104 views
0

晚上好,我想從用戶點擊的行中獲取所有的數據,所以我試過這個腳本,它獲取了行ID,但它沒有得到數據存在該行,我說行中的每個數據推到一個數組用於其它用途:JavaScript獲取點擊行的數據

function findRowNumber() { 
    var rowIdx; 
    var rowData = new Array(); 
    var table = document.getElementById('product_table'); 
    var rows = table.getElementsByTagName('tr'); 
    var selectedRow; 
    var rowCellValue; 
    for (i = 0; i < rows.length; i++) { 
     rows[i].onclick = function() { 
      rowIdx = this.rowIndex; 
      selectedRow = rows[rowIdx]; 
      for (j = 1; j < selectedRow.length; j++) { // it doesn't enter that loop 
     rowCellValue = selectedRow.cells[j].value; 
     rowData.push(rowCellValue); 
     alert("Value " + rowCellValue); 

    } 
     } 
    } 


} 

回答

2

selectedRow之後您填充單擊該行,而你要綁定單擊處理後試圖循環低谷,但前實際點擊。你必須移動代碼在單擊處理

+0

我搬到循環到單擊處理程序,但沒有改變它仍然沒有得到警告 – 2013-03-06 14:17:33

+0

@Eslam我想是沒有定義的rowIndex值:) – 2013-03-06 15:07:50

0

如果在單元格中的數據是文本,

它可能是簡單的檢索與的textContent(或innerText屬性)。

<!doctype html> 
<html lang= "en"> 
<head> 
<meta charset= "utf-8"> 
<title> Small Test Page</title> 
<style> 
table{border:3px ridge #c0c0c0;border-collapse:collapse;} 
th, td{border:1px solid black} 
</style> 

<script>  
function findRowNumber(){ 
    var rowIdx; 
    var rowData= []; 
    var table= document.getElementById('product_table'); 
    var rows= table.getElementsByTagName('tr'); 
    var selectedRow; 
    var rowCellValue; 
    for(i= 0;i<rows.length;i++){ 
     rows[i].onclick= function(){ 
      rowIdx= this.rowIndex; 
      selectedRow= this.cells; 
      for(j= 0;j<selectedRow.length;j++){ 
       rowCellValue= selectedRow[j].textContent || 
       selectedRow[j].innerText; 
       rowData.push('cell '+j+': '+rowCellValue); 
      } 
      alert("Row #" +rowIdx+'. '+ rowData); 
     } 
    } 
}  
</script> 
</head> 
<body> 
<h1> Retrieve Row Data</h1> 
<p> <button type= "button" id= "tableSwapBtn" onclick= "findRowNumber()"> 
Click to initialize</button> </p> 

<table id="product_table" style="width:300px"> 
<tbody> 
<tr> <td> a</td> <td> 1</td> </tr> 
<tr> <td> b</td> <td> 2</td> </tr> 
<tr> <td> c</td> <td> 3</td> </tr> 
<tr> <td> d</td> <td> 4</td> </tr> 
<tr> <td> e</td> <td> 5</td> </tr> 
<tr> <td> f</td> <td> 6</td> </tr> 
<tr> <td> g</td> <td> 7</td> </tr> 
</tbody> 
</table> 
</body> 
</html>