$(function () {
var flag=true;
$(".loginitem-pre").on('click', function () {
Check("txtPhone");
console.log(flag)
Check("personnal");
console.log(flag)
Check("txtarea");
console.log(flag)
Check("code");
if(flag){
$.ajax({
type: 'post',
async:false,
url: 'post.php?ajax=1',
dataType:"json",
data: $("form").serialize(),
success:function(data){
console.log(data)
if(true){
layer.open({
content: '保存成功'
,btn: ['确定']
,style: 'background-color:#ffffff; color:#000000; border:none; width: 2rem;line-height:.5rem' //自定风格'
,time: 5
});
};
flag=false;
}
});
};
});
});
function Check(id) {
var regStr = "";
var sResult = "";
var txt = $.trim($("#" + id).val());
console.log(txt)
if (txt =='') {
sResult = "各项不能为空";
layer.open({
content: sResult
,btn: ['确定']
,style:'background-color:#ffffff; color:#000000; border:none; width: 2rem;line-height:.5rem' //自定风格'
});
flag=false;
return;
}
else {
switch (id) {
case "personnal":
regStr = /[\u4E00-\u9FA5]{2,4}/;
break;
case "txtPhone":
regStr = /0?(13|14|15|18)[0-9]{9}/;
break;
}
if (regStr && regStr.test && !regStr.test(txt)) {
sResult = "输入的内容格式不对";
layer.open({
content: sResult
,btn: ['确定']
,style:'background-color:#ffffff; color:#000000; border:none; width: 2rem;line-height:.5rem' //自定风格'
});
flag=false;
return;
}
}
}
1:首第一个问题是为什么我打印出来的flag=ture;无论下面有没有输入内容以及格式对不对;都是可以提交;
2;第二就是当我把全局变量 var flag=true;改为 var flag;然后打印出的是undefined;请问我这个问题提出在哪里;
3;我的需求就是验证表单;错误时弹出对应的提示和阻止提交;验证成功时;阻止重复提交
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
html贴出来吧,我有点怀疑你id写错了
console.log(txt);console.log($("#" + id));得到什么?
你这样写,出现了异步执行;意思就是你的Check没跑完,就log了。建议你去脑补下js 异步编程的相关知识。
把几个判断放在if代码块中,这样能保证验证正确执行完
其实好久没有使用 console 调试了,因为 chrome 本身的断点调试就很棒了
然后,就是前端没有图片的代码问题放在 jsbin.com、jsfiddle.net 等网站上效果会更好一些,一方面有空帮忙调试的同学更带感,另一方面也的确能节省彼此的时间
代码要对齐!代码要对齐!代码要对齐!重要的事情说三遍。
解决方案,把
Check(id)方法放进$(function () {}里面,至于为什么,自己想吧。闭包该好好复习一下了。
补充:方案2