JS 獲取table表的數據,生成json

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"> 
	<title>Bootstrap 實例 - 邊框表格</title>
	<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
	<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<table class="table table-bordered" id="custom-table">
	<caption>邊框表格佈局</caption>
	<thead>
		<tr>
			<th>序號</th>
			<th>城市</th>
			<th>郵編</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<th>1</th>
			<td>Bangalore</td>
			<td>560001</td>
		</tr>
		<tr>
			<th>2</th>
			<td>Mumbai</td>
			<td><select><option>400003</option><option>400004</option></select></td>
		</tr>
		<tr>
			<th>3</th>
			<td>Pune</td>
			<td><input type="text" value="411027"/></td>
		</tr>
	</tbody>
</table>

</body>
<script type="text/javascript">
	var trs = $("#custom-table tr");
	var result = [];
	for (var i = 1; i < trs.length; i++) {
		var tds = $(trs[i]).find("td");
		var inputValue = $(tds[1]).find("input").html();
		var selectValue = $(tds[1]).find("select").html();
		var data={};
		data['name']=$(tds[0]).html();
		if(inputValue == undefined && selectValue == undefined){
			data['value']=$(tds[1]).html();
		}else if(inputValue != undefined){
			data['value']=tds[1].getElementsByTagName("input")[0].value;
		}else if(selectValue != undefined){
			data['value']=tds[1].getElementsByTagName("select")[0].value;
		}
		result.push(data);
	}
	console.log(result);
</script>
</html>

這是打印結果result:

 

如果是獲取固定表格的input的值,可以直接通過input的id 來獲取  $(tds[1]).find("input[id='12']").val();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章