我有一段简单的代码,我认为应该可以工作
HTML
<table cellpadding="0" cellspacing="0" border="0">
<tbody><tr>
<th scope="row">Quantity</th>
<th id="js-QuantityID-1" scope="col">1</th>
<th id="js-QuantityID-2" scope="col">2</th>
<th id="js-QuantityID-3" scope="col">3</th>
<th id="js-QuantityID-4" scope="col">4</th>
<th id="js-QuantityID-5" scope="col">5</th>
<th id="js-QuantityID-6" scope="col">10</th>
<th id="js-QuantityID-7" scope="col">15</th>
<th id="js-QuantityID-8" scope="col">20</th>
<th id="js-QuantityID-9" scope="col">30</th>
<th id="js-QuantityID-10" scope="col">40</th>
<th id="js-QuantityID-11" scope="col">100</th>
</tr>
<tr>
<th scope="row">Price (inc. VAT)</th>
<td id="js-PriceID-1">£45.60</td>
<td id="js-PriceID-2">£76.80</td>
<td id="js-PriceID-3">£97.20</td>
<td id="js-PriceID-4">£128.40</td>
<td id="js-PriceID-5">£172.80</td>
<td id="js-PriceID-6">£307.20</td>
<td id="js-PriceID-7">£402.00</td>
<td id="js-PriceID-8">£432.00</td>
<td id="js-PriceID-9">£630.00</td>
<td id="js-PriceID-10">£840.00</td>
<td id="js-PriceID-11">£2100.00</td>
</tr>
</tbody>
</table>
Javascript
function getTableContents() {
var productArray = [];
for (var x = 0; x <= 12; x++) {
productArray.push({ Price: $('#js-PriceID-' + x).text(), Qty: $('#js-QuantityID-' + x).text() });
}
console.log("Array: " + productArray);
}
但在执行此代码结束时,我最终得到一个具有两个属性“未定义”的数组。如果我手动输入选择器 ID,它工作正常,它似乎与 for 循环一起使用并在运行时获取值。
这是为什么?有解决方法吗?
最佳答案
循环中的第一项是 0,最后一项是 12。这就是原因。
按如下方式尝试循环:
for (var x=1; x<=11; x++)
关于javascript - 将对象推送到数组,并使用属性选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31126104/