jQuery Smart Wizard验证失败时如何阻止跳转到下一步?
问题根源
你用错了SmartWizard的拦截事件:
stepContent是步骤跳转完成、内容已经加载后才触发的回调,此时跳转逻辑已经执行完毕,你在这个回调里return false自然无法拦截跳转- 单独绑定
.sw-btn-next的click事件无效,是因为SmartWizard内部已经提前绑定了该按钮的事件处理逻辑,自定义click事件优先级不够,无法覆盖内置逻辑
修复方案
改用SmartWizard 5.x版本提供的stepChange事件,这个事件是跳转动作触发前、还未执行切换逻辑的时候触发的,只要在这个事件里验证不通过时return false就能直接拦截跳转。
修改后的SmartWizard配置代码如下:
// ################################### // # jQuery SmartWizard plugin // ################################### $('#smartwizard').smartWizard({ selected: 0, // Initial selected step, 0 = first step theme: 'default' // theme for the wizard, related css need to include for other than default theme // 跳转前验证:用stepChange事件 }).on("stepChange", function(e, anchorObject, currentStepIndex, nextStepIndex, stepDirection) { // 只有向前跳转才做验证 if (stepDirection == 'forward') { if ($('#addNewUser').valid()) { console.log('Form on Step ' + currentStepIndex + ' is valid'); return true; } else { console.log('Form on Step ' + currentStepIndex + ' is invalid'); // 验证失败返回false直接阻止跳转 return false; } } // 跳转完成后的后续操作:原来的stepContent逻辑保留 }).on("stepContent", function(e, anchorObject, stepIndex, stepDirection) { // 检查是否到第5步,控制提交按钮显隐 $('#newUserSubmit').prop('disabled', stepIndex !== 4); console.log('Navigated to stepIndex ' + stepIndex + ' moving in stepDirection ' + stepDirection); });
可选优化
如果你的表单是分步骤拆分到不同的<form id="form-step-x">里,不需要每次都验证整个表单,可以只验证当前步骤的表单,逻辑和上面一致,只要把$('#addNewUser').valid()改成对应步骤的表单实例的valid()调用即可。
内容的提问来源于stack exchange,提问作者Armitage2k
相关产品推荐
相关产品推荐

