jQuery each方法为多同构自定义搜索表单追加URL查询串时跨表取值异常
问题原因
核心错误是绑定点击事件时使用了全局选择器$('.custom-search-btn'),没有限定在当前遍历的.custom-search容器范围内,导致:
- 每个表单循环都会给页面上所有的搜索按钮重复绑定事件
- 闭包引用的下拉框取值会被后续循环覆盖,最终取到的始终是最后一个表单的元素值
修复后的实现代码
推荐直接使用动态关联方式,无需预先遍历绑定,代码更简洁且不会出现取值混乱:
$('.custom-search-btn').on('click', function(e) { e.preventDefault(); // 根据当前点击的按钮,向上找到所属的自定义搜索表单容器 const $currentForm = $(this).closest('.custom-search'); // 仅在当前表单范围内查找对应下拉框的值 const minPrice = $currentForm.find('.price-min').val(); const maxPrice = $currentForm.find('.price-max').val(); const productName = $currentForm.find('.product').val(); // 拼接跳转URL const redirectUrl = `/products/?product-view=1&minPrice=${encodeURIComponent(minPrice)}&maxPrice=${encodeURIComponent(maxPrice)}&productName=${encodeURIComponent(productName)}`; window.location.href = redirectUrl; });
如果需要保留原有的.each遍历结构,可按如下方式修改:
$('.custom-search').each(function () { const $currentForm = $(this); // 预存当前表单对应的下拉框元素 const $minPrice = $currentForm.find('.price-min'); const $maxPrice = $currentForm.find('.price-max'); const $product = $currentForm.find('.product'); // 仅在当前表单范围内查找搜索按钮,避免全局绑定 $currentForm.find('.custom-search-btn').on('click', function(e) { e.preventDefault(); const redirectUrl = `/products/?product-view=1&minPrice=${encodeURIComponent($minPrice.val())}&maxPrice=${encodeURIComponent($maxPrice.val())}&productName=${encodeURIComponent($product.val())}`; window.location.href = redirectUrl; }); });
额外说明
- 新增
e.preventDefault()是因为按钮的type为submit,阻止默认表单提交行为,避免触发浏览器默认的提交逻辑打断跳转流程 - 使用
closest('.custom-search')可以精准定位到当前按钮所属的表单容器,不受其他同结构表单的影响
内容的提问来源于stack exchange,提问作者Robin H.
相关产品推荐
相关产品推荐

