我正在处理表上的一些数字字段。该表包含商品名称、单价和归档数量,即数量。每次金额增加或减少时,我想要一个产品/商品数组,其中包含 商品名称
、商品单价
、商品金额
、该商品的总价
。
例如这样
items =
[
['Name', '5', '2', '10'],
['Name2', '15', '2', '30'],
]
如果数量零
那么该项目将不会出现在数组中。
jQuery(document).ready(function() {
jQuery(document).on('input', '.se-ticket-qty', function() {
var items = GetItems();
// jQuery('input#items').val(items);
console.log(items);
});
function GetItems() {
jQuery(".se-ticket-qty").each(function(index) {
var items = [];
var item_name = jQuery(this).data('name');
var unit_price = parseFloat(jQuery(this).data('unit-price'));
var amount = parseFloat(jQuery(this).val());
var totalPrice = unit_price * amount;
items = [item_name, unit_price, amount, totalPrice];
});
return items;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Front Row</th>
<td><span class="se-curency">$ </span>5</td>
<td>
<input min="0" data-name="Front Row" data-unit-price="5" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<th>VIP Seat</th>
<td><span class="se-curency">$ </span>10</td>
<td>
<input min="0" data-name="VIP Seat" data-unit-price="10" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
</table>
最佳答案
您正在将项目
重新分配给新数组
- 在每个 block 之外初始化数组
- 使用
.push()
填充新数组元素的方法 - 使用
.data()
方法时,请使用camelCase,即unitPrice
作为虚线键。 - 添加零的条件语句
代码
function GetItems() {
var items = []; //Initialize
jQuery(".se-ticket-qty").each(function(index) {
var item_name = jQuery(this).data('name');
var unit_price = parseFloat(jQuery(this).data('unitPrice'));
var amount = parseFloat(jQuery(this).val());
//Add condtion for zero
if (amount > 0) {
var totalPrice = unit_price * amount;
items.push([item_name, unit_price, amount, totalPrice]); //Use push
}
});
return items;
}
jQuery(document).on('input', '.se-ticket-qty', function() {
var items = GetItems();
console.clear();
console.log(items);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Front Row</th>
<td><span class="se-curency">$ </span>5</td>
<td>
<input min="0" data-name="Front Row" data-unit-price="5" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<th>VIP Seat</th>
<td><span class="se-curency">$ </span>10</td>
<td>
<input min="0" data-name="VIP Seat" data-unit-price="10" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
</table>
关于javascript - 从输入数据值创建 Javascript 多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51017104/