点击Next按钮无法切换fieldset问题求助(无控制台错误)
问题分析与解决方案
问题根源
你的代码中,current_fs = $(this).parent(); 和 next_fs = $(this).parent().next(); 错误定位了元素:
.next按钮的父元素是.f_btn,它的同级元素并非下一个<fieldset>,而是页面内的其他div节点- 这导致代码无法正确选中需要切换的fieldset,自然无法触发显示/隐藏逻辑
修复代码
修改JavaScript中获取current_fs和next_fs的逻辑,通过closest()方法找到当前按钮所在的fieldset,再用next()定位下一个fieldset:
$(document).ready(function() { var current_fs, next_fs, previous_fs; //fieldsets var opacity; var current = 1; var steps = $("fieldset").length; $(".next").click(function() { // 修正:找到当前按钮所在的fieldset current_fs = $(this).closest("fieldset"); // 修正:定位下一个fieldset next_fs = current_fs.next(); //show the next fieldset next_fs.show(); //hide the current fieldset with style current_fs.animate({ opacity: 0 }, { step: function(now) { // for making fielset appear animation opacity = 1 - now; current_fs.css({ 'display': 'none', 'position': 'relative' }); next_fs.css({ 'opacity': opacity }); }, duration: 500 }); }); $("#msform").on("submit", function(e) { e.preventDefault(); }); });
额外优化建议
- 可以添加边界判断,当处于最后一个fieldset时,隐藏Next按钮或给出提示
- 动画逻辑中,可提前将
next_fs的初始opacity设为0,避免切换时突兀显示
内容的提问来源于stack exchange,提问作者Jessica Kimble
相关产品推荐
相关产品推荐

