想知道如何讀取表格單元格,每個單元格數據都在其中。表格和示例代碼的示例在這裏http://jsfiddle.net/ccvq05br/7/ JavaScript函數未在jsfiddle中調用。我做錯了嗎?!'div'到'class'內的訪問表單元格數據
我不能使用id,因爲它用於其他計算,有沒有辦法使用類名或否則?想要訪問單元沒有它的ID!
jsfiddle中的JavaScript代碼沒有被調用。我的代碼中有沒有問題?
HTML代碼:
<br>
<table id="tableID" border="1">
<thead>
<tr>
<th>Data1</th>
<th>Data2</th>
<th>Data3</th>
<th>Data4</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" class ="data1" name="val1" id="ChkBox_M21">
</td>
<td>
<div class="form-group">
<select class="form-control" class="data2" name="val2" id="Data_M21" >
<option value='1' selected>1</option>
<option value='2' >2</option>
<option value='3' >3</option>
</select>
</div>
</td>
<td>
<input class="data3" size="4" name="val3" type="text" id="Txt_M31">
</td>
<td>
<div class="form-group">
<select class="form-control" class="data4" name="val4" id="Data_M21" >
<option value='Opt1' selected>Opt1</option>
<option value='Opt2' >Opt2</option>
<option value='Opt3' >Opt3</option>
</select>
</div>
</td>
</tr>
<!-- 2nd row -->
<tr>
<td>
<input type="checkbox" class ="data1" name="val1" id="ChkBox_M21">
</td>
<td>
<div class="form-group">
<select class="form-control" class="data2" name="val2" id="Data_M21" >
<option value='1' selected>1</option>
<option value='2' >2</option>
<option value='3' >3</option>
</select>
</div>
</td>
<td>
<input class="data3" size="4" name="val3" type="text" id="Txt_M31">
</td>
<td>
<div class="form-group">
<select class="form-control" class="data4" name="val4" id="Data_M21" >
<option value='Opt1' selected>Opt1</option>
<option value='Opt2' >Opt2</option>
<option value='Opt3' >Opt3</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>
<br><br>
<input type="button" value="Read Data" onclick="callFunc()"/>
JavaScript代碼:
function callFunc(){
alert("hi");
var oTable = document.getElementById("tableId");
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
/* get the cell info of first row
How to get values of each cell which is inside div
and only can use 'class' to identify specific cells in a row.
id is used for some calculation purpose.
*/
var cell1Val = oCells.item(0).innerHTML;
alert("cell 1 value : " + cellVal);
var cell1Val = oCells.item(1).innerHTML;
alert("cell 2 value : " + cellVal);
var cell1Val = oCells.item(2).innerHTML;
alert("cell 3 value : " + cellVal);
var cell1Val = oCells.item(3).innerHTML;
alert("cell 4 value : " + cellVal);
}
}
您是否嘗試過getElementByClassName()方法? http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp – Anfuca
我想所有列的所有列的名稱都相同!我無法使用document.getElementsByClassName。如何通過getElementsByClassName來訪問一個單元格 – SKay