jQuery输入框值获取异常求助:切换quantity/discount时对应值为undefined
问题分析与解决方案
我一眼就看出问题出在哪了,咱们一步步拆解:
核心问题
错误的元素查找范围:
当你修改#quantityNumbeInvoiceItem时,你用$(this).parent('td').find('#itemDiscountInvoice')去查找折扣输入框,但折扣输入框在相邻的td里,不是当前输入框的父td内,所以这个查找会返回空的jQuery对象,取它的值自然就是undefined。同理,修改折扣输入框时,你在它的父td里找数量输入框,也找不到,结果同样是undefined。没有获取输入框的实际值:
你把jQuery元素对象(比如quantity变量是选中的输入框元素)直接拼到URL里,而不是获取它的value值,这会导致URL里出现[object Object]这类无效内容,AJAX请求自然拿不到正确参数。
修正后的jQuery代码
调整查找范围并正确获取输入值,同时做了一些健壮性优化:
$(document).on('change keyup', '#quantityNumbeInvoiceItem, #itemDiscountInvoice', function() { // 先定位当前输入框所在的行,所有相关元素都基于这一行查找 const $currentRow = $(this).closest('tr'); // 从当前行内获取各个元素的实际值 const quantity = $currentRow.find('#quantityNumbeInvoiceItem').val(); // 去掉折扣值里的$符号,避免传递无效字符给后端 const discount = $currentRow.find('#itemDiscountInvoice').val().replace('$', ''); const item_name = $currentRow.find('#itemNameJsAjax span').text().trim(); // 对参数进行编码,避免特殊字符(如空格、&)导致URL解析错误 const ajaxUrl = `requests/Ajax/item_full_amount.php?item_name=${encodeURIComponent(item_name)}&quantity=${encodeURIComponent(quantity)}&discount=${encodeURIComponent(discount)}`; const itemContainer = $currentRow.find('#fullAmountForItemJsAjax'); $.ajax({ url: ajaxUrl, type: 'GET', }) .done(function(res) { itemContainer.html(res); }) .fail(function() { console.log("error"); }); });
额外优化建议
- 用
closest('tr')代替多次parent('td').parent('tr'),代码更简洁健壮,哪怕DOM结构微调(比如td里多嵌套了div),也能正确定位到当前行。 - 注意你的输入框id拼写:
quantityNumbeInvoiceItem少了一个r(应该是quantityNumberInvoiceItem),如果页面有多行商品,重复的id会违反HTML规范,建议改成class选择器,比如把id="quantityNumbeInvoiceItem"改成class="quantityNumberInvoiceItem",然后jQuery里用$currentRow.find('.quantityNumberInvoiceItem')查找,避免id冲突问题。
内容的提问来源于stack exchange,提问作者alaa nabawy
相关产品推荐
相关产品推荐

