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();

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值