我需要将所有td值放入字符串数组中。以下是我的代码
var tr = "#tblPurchaseOrders tr.PO1";
$(tr).each(function(index, tr) {
var lines = $(tr + " td").map(function(ind, td) {
var ret = {};
ret[ind] = $(td).text();
return ret;
}).get();
// I need to some more thing here
// I need to store all the td values in to lines variable.. This is not working for me.
// Am I missing some thing?
});
感谢。
答案 0 :(得分:15)
试试这样:
$('#tblPurchaseOrders tr.PO1').each(function(index, tr) {
var lines = $('td', tr).map(function(index, td) {
return $(td).text();
});
// Here lines will contain an array of all td values for the current row:
// like ['value 1', 'value 2', 'value 3']
});
答案 1 :(得分:2)
Darin Dimitrov的代码非常有帮助。我将其修改为从点击中拉出来。
$('#tblPurchaseOrders tr').click(function(){
$(this, 'tr').each(function(index, tr) {
var lines = $('td', tr).map(function(index, td) {
return $(td).text();
});
//This assumes that you have a table with an id of tblPurchaseOrders and that you have two cells of data
alert(lines[0] + ' ' + lines[1]);
})
});
答案 2 :(得分:0)
假设row
是jQuery选择器的结果,可以使用以下方法将数据检索为数组:
function get_row_as_array(row) {
var data = $('td', row).map(function(index, value) {
return $(value).text();
});
return data;
}
我将这个答案作为一般情况提交给那些只需要一个表行数据的人。
$(document).ready(function() {
function get_row_as_array(row) {
var data = $('td', row).map(function(index, value) {
return $(value).text();
});
return data;
}
var row = $('#alphabet tr:eq(1)');
var result = get_row_as_array(row);
$('#alphabet tr:eq(2) td:eq(2)').html(result[2]);
});

table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Get Table Row as Array</title>
</head>
<body>
<table id="alphabet">
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
</tr>
<tr>
<td>Alpha</td>
<td>Bravo</td>
<td>Charlie</td>
<td>Delta</td>
<td>Echo</td>
</tr>
<tr>
<td>Empty</td>
<td>Empty</td>
<td>Empty</td>
<td>Empty</td>
<td>Empty</td>
</tr>
</table>
</body>
</html>
&#13;