【发布时间】:2018-06-30 08:19:01
【问题描述】:
我正在尝试将事件绑定到输入字段。当 input 的值被改变时,该事件应该被触发(不管它是如何改变的)。
输入元素首先被附加,我认为它没有应用事件。
就是将元素添加到表格中的功能,现在我需要检查输入字段的值,如果输入字段随时更改,我必须更改表格内的总价。
下一个问题是当我尝试检查项目是否已经添加到表中时,如果项目在表中,那么我应该增加其输入字段的值,如果它是一个新项目,那么它应该填充表有数据。
$(document).ready(function() {
// Document is ready.
var data = {};
console.log('log');
$('.tile').bind('click', addOrder);
$(document).on('change', '.quantitiy', inputTotal);
});
function inputTotal() {
console.log($(this).val());
}
function addOrder() {
var anchor_id = $(this).children('div').find('.id').html();
var anchor_name = $(this).children('div').find('.name').html();
var anchor_price = $(this).children('div').find('.price').html();
var anchor_number = $(this).children('div').find('.number').html();
data = {
'product_id': anchor_id,
'product_name': anchor_name,
'product_price': anchor_price,
'product_quantity': anchor_number
};
var rows = $('#orders tr');
if( rows.length === 0 ) {
populateTable();
console.log('new item');
} else {
console.log('checking items');
checkTableItems(rows, anchor_id);
}
}
function checkTableItems(rows, id) {
$.each(rows, function(key, value) {
console.log(key + ' - ' + $(value).find('.productID').html());
console.log(id + ' - ' + $(this).find('.productID').html());
if( id === $(value).find('.productID').html()) {
console.log('increase quantity if item match');
$(value).find('input').val( +$(value).find('input').val()+1 );
return false;
} else {
populateTable();
}
});
}
function populateTable() {
var order_close = '<td><button href="#" class="btn default red-stripe"><i class="fa fa-close"></i></button></td>';
var order_name = '<td class="productname"><div class="productID" style="display:none">'+data.product_id+'</div>'+data.product_name+'</td>';
var order_price = '<td>'+data.product_price+'</td>';
var order_quantity = '<td class="hidden-xs" ><div class="form-group"><div class="input-inline input-small"><input type="text" value="1" name="demo1" class="quantity form-control touchspin_demo1" ></div></div></td>';
$('#orders').append('<tr>'+order_close+order_name+order_quantity+order_price+'<td class="total">1</td></tr>');
ComponentsFormTools.init();
}
我做错了什么,因为当我更改它的值时绑定事件不会触发,并且 checkTableItems 只读取行中的第一个元素。
PS。我想我在 $.each 循环中有错误的选择器或错误的逻辑......
编辑:更改文档就绪,并将 inputTotal 置于 jQuery 就绪函数之外,仍然没有触发事件。
【问题讨论】:
-
$.when( $.ready )的预期结果是什么? -
您可以通过在需要的地方添加此行来手动触发事件$(“.tile”).trigger(“click”)
-
@maddy23285 这不是我需要做的。我无法手动触发它,我需要它随时工作......
标签: javascript jquery html