Dot*_*mer 34 html foreach jquery loops
我正在尝试获取html中的数据<tbody>.基本上,我有很多这样的行;
<tbody>
<tr>
<td>63</td>
<td>Computer</td>
<td>3434</td>
<td>
<button class="btn-medium btn-danger remove" id="mprDetailRemove"><i class="icon-remove"></i></button>
</td>
</tr>
<tr>
<td>64</td>
<td>Stationary</td>
<td>111</td>
<td>
<button class="btn-medium btn-danger remove" id="Button1"><i class="icon-remove"></i></button>
</td>
</tr>
<tr>
<td>64</td>
<td>Stationary</td>
<td>11</td>
<td>
<button class="btn-medium btn-danger remove" id="Button2"><i class="icon-remove"></i></button>
</td>
</tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)
现在,我正在循环并尝试获得这样的<td>值;
var table = $("#mprDetailDataTable table tbody");
table.find('tr').each(function (key, val) {
$(this).find('td').each(function (key, val) {
var productId = val[key].innerHTML; // this isn't working
var product = ?
var Quantity = ?
});
});
Run Code Online (Sandbox Code Playgroud)
但是,我无法获得每行的值(html文本).我想将这些值分配给局部变量.
另外,我不想得到innerHTML一个按钮(在每一行)
nnn*_*nnn 70
使用嵌套.each()意味着您的内部循环一次执行一个td,因此您无法在内部循环中设置productIdand product和quantityall.
也使用function(key, val)然后val[key].innerHTML是不对的:该.each()方法传递索引(一个整数)和实际元素,所以你使用function(i, element)然后element.innerHTML.虽然jQuery也设置this了元素,所以你可以这么说this.innerHTML.
无论如何,这是一种让它工作的方法:
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
});
Run Code Online (Sandbox Code Playgroud)
试试这个
$("#mprDetailDataTable tr:gt(0)").each(function () {
var this_row = $(this);
var productId = $.trim(this_row.find('td:eq(0)').html());//td:eq(0) means first td of this row
var product = $.trim(this_row.find('td:eq(1)').html())
var Quantity = $.trim(this_row.find('td:eq(2)').html())
});
Run Code Online (Sandbox Code Playgroud)