![](/img/trans.png)
[英]Javascript function inside if statement still runs even though condition is not met
[英]Form submitting even though it's encased in an if statement, and condition is not met?
我已经将整个验证代码绑定到$('#post-button').click
。 这个想法是,将变量e_exit
设置为true
,然后表单中的数据将进行一系列检查。 如果满足任何if语句的条件,则会显示一条带有问题的消息,并且e_exit
设置为false
。 唯一的问题是,由于表单仍在提交(显示消息后的四分之一秒),因此操作不正确。
我在这里处理布尔值,所以类型转换当然不是问题,我真的不明白发生了什么:
$('#post-button').click( function() {
var e_exit = true;
var notif_message = '<div class="notification red"><div class="cross"></div>';
var name = $('input[name=name]').val();
var url = $('input[name=url]').val();
var urlrgx = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/i;
var urltst = urlrgx.test(url);
if(name == '' || name == 'Enter a name for this offer') {
$('#notification').html(notif_message + "You need to enter a name for this offer name. Try to pick something that you'll easily remember when seen again.</div>");
e_exit = false;
}
if(!urltst) {
$('#notification').html(notif_message + "You need to enter a valid offer url prefixed with http:// for this offer.</div>");
e_exit = false;
}
var rotation_select_val = parseInt($('select[name=r_id]').val());
if(rotation_select_val != 0) {
var min_val = isNaN($('input[name=r_min]').val());
var max_val = isNaN($('input[name=r_max]').val());
if(min_val || max_val) {
$('#notification').html(notif_message + "You need to enter a numeric value for your rotation's min and max hits for this offer.</div>");
e_exit = false;
}
}
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
if(geo_select_val != 0) {
var geo_url_val = $('input[name=g_url\\[1\\]]').val();
var geo_urltst = urlrgx.test(geo_url_val);
if(!geo_urltst) {
$('#notification').html(notif_message + "You need to enter a valid url prefixed with http:// for your geo-location targets.</div>");
e_exit = false;
}
}
if(e_exit) {
$('form').submit();
}
});
关于为什么会发生这种情况的任何答案,或者带有解释的编辑都将大有帮助!
如果#post-button
是一个提交按钮,则需要返回false
以停止表单提交。
更好的解决方案是绑定到表单的submit
事件:
$("#your-form").submit(function() {
// validate...
return e_exit;
});
如果您从事件处理程序返回true
,则仅允许表单提交。
编辑:
也许ajax插件还订阅了发布按钮的click
事件? 在这种情况下,我将返回false并确保停止进一步传播事件,如下所示:
$("#post-button").click(function(ev) {
// validation
ev.stopPropagation();
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.