如何识别表单字段数量并修复JS条件判断匹配错误问题
错误原因
- 字段计数时机错误:你在页面初始化阶段就全局计算了字段长度,没有在点击表单时针对当前被点击的表单单独统计,计数和实际点击的表单不匹配
- 判断条件逻辑错误:
>=0的判断永远成立,因为即使表单中不存在对应字段,jQuery选择器返回的长度也是0,所以5字段表单的判断条件永远为真,2字段分支永远不会触发 - 语法错误:代码中使用了中文双引号包裹字符串,会直接触发JS语法报错
修复后代码
如果你只需要按字段数量判断表单类型,可使用以下代码:
$('.Form').on('click', function(event) { event.stopPropagation(); event.stopImmediatePropagation(); const $currentForm = $(this); // 优先判断MQL表单 if ($currentForm.data('mql') === 'yes' || $currentForm.data('mql') === 1) { alert("MQL"); return; } // 统计当前表单的字段数量 const inputCount = $currentForm.find('input').length; const selectCount = $currentForm.find('select').length; // 按规则判断表单类型 if (inputCount === 4 && selectCount === 1) { alert("five fields form"); } else if (inputCount === 2 && selectCount === 0) { alert("two fields form"); } // 其他类型表单可在此补充逻辑 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
如果你需要严格匹配指定字段是否存在而非仅统计数量,可使用以下代码:
$('.Form').on('click', function(event) { event.stopPropagation(); event.stopImmediatePropagation(); const $currentForm = $(this); // 优先判断MQL表单 if ($currentForm.data('mql') === 'yes' || $currentForm.data('mql') === 1) { alert("MQL"); return; } // 统计当前表单指定字段是否存在 const hasEmail = $currentForm.find("input[name='Email']").length > 0; const hasFirstname = $currentForm.find("input[name='FirstName']").length > 0; const hasLastname = $currentForm.find("input[name='LastName']").length > 0; const hasCompany = $currentForm.find("input[name='Company']").length > 0; const hasCountry = $currentForm.find("select[name='Country']").length > 0; if (hasEmail && hasFirstname && hasLastname && hasCompany && hasCountry) { alert("five fields form"); } else if (hasEmail && hasCountry) { alert("two fields form"); } });
内容的提问来源于stack exchange,提问作者Yan Mak
相关产品推荐
相关产品推荐

