我对 JavaScript 和 jQuery 还很陌生。我知道我的代码不是最漂亮的,但我正在尝试从某个地方开始。
我有一系列问题,一次显示一个问题,我想创建某种验证,以防止用户在第一个按钮上的单选按钮未被选中时转到下一个问题。
HTML(我有四个 .questionContainers
<div class="questionContainer">
<div class="question">
How much storage do you need?
</div>
<div class="answers">
<ul>
<li>
<label>
<input type="radio" id="storage">1GB or less
</label>
</li>
<li>
<label>
<input type="radio" id="storage">More than 1GB
</label>
</li>
</ul>
</div>
<div class="btnContainer">
<div class="next">
<a class="btnNext">Next</a>
</div>
</div>
</div>
JavaScript
(function(){
var Questions = {
container : $('.questionContainer'),
init : function() {
this.start();
if($('input[type=radio]:checked').length > 0){
this.container.find('a.btnNext').on('click', this.next);
}
},
start : function() {
this.container.not(':first').addClass('hide');
},
next : function() {
var container = $('.questionContainer');
$(this).closest(container).hide(function(){
$(this).closest(container).next().show();
});
}
};
Questions.init();
})();
具体行不通:
if($('input[type=radio]:checked').length > 0) {
this.container.find('a.btnNext').on('click', this.next);
}
问题
当我添加 if 语句并单击单选按钮后跟下一步时,它不会转到下一个问题。我在控制台中没有收到任何错误。
最佳答案
只有在调用启动函数时检查了某些内容(不是您想要的 - 它永远不会是真的,除非您为用户没有他们的行动):
if($('input[type=radio]:checked').length > 0){
this.container.find('a.btnNext').on('click', this.next);
}
尝试用这个替换它:
this.container.find('a.btnNext').on('click', function () {
if($('input[type=radio]:checked').length > 0){
this.next();
}
});
这样你总是绑定(bind)到点击事件,但是绑定(bind)的函数只允许调用 next
如果在调用函数时检查了某些东西(即当下一个按钮被点击)。
关于javascript - jQuery 如果单选按钮被选中则继续下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22312176/