所以我已经通过持续的研究和教程研究了一段时间,但我似乎无法找到我做错了什么。
我有一个看起来像这样的按钮
按钮 id="create_account"
请忽略它缺少一个类等等,它都在那里,但 Stack Overflow 对我来说很棘手,这不是我卡住的地方。
单击按钮后,它会运行一个 java 脚本代码
$(document).on("click", "#create_account", function(evt)
{
/* this code here is not mine, found it in an online tutorial and the jsfiddle of it works, so i know this isnt the problem */
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if(inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("Not a valid Phone Number");
return false;
}
}
});
我有点知道为什么这不起作用,原因是我没有要求运行该特定函数,但我知道它在一些测试后点击了它的 onclick 方面。
我想做的是将电话号码验证为 10 位数字(目前),我的输入类型为文本,id 为 input_phone,稍后我将修改该修改以用于超过 10 个数字,但我一直在执行此功能并弹出警报。
提前感谢您的任何提示/帮助!
最佳答案
它不起作用,因为您是在点击事件中定义一个函数,而不是调用它。您可以将函数体移到事件回调之外,只需从内部调用函数即可。
类似这样的事情(我也忽略了缺失的变量等,只是向您展示了方法):
$(document).on("click", "#create_account", function(evt)
{
phonenumber($('#create_account').val()); // or whatever the input value is
})
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if(inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("Not a valid Phone Number");
return false;
}
}
$(document).on("click", "#create_account", function(evt) {
console.log(phonenumber($('#in').val()) ? 'Valid' : 'Invalid');
})
function phonenumber(inputtxt) {
var phoneno = /^\d{10}$/;
if (inputtxt.match(phoneno)) {
return true;
} else {
alert("Not a valid Phone Number");
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="in" />
<button id="create_account">Create Account</button>
纯 JS 版本
document.getElementById('create_account').addEventListener('click', function(evt) {
console.log(phonenumber(document.getElementById('in').value) ? 'Valid' : 'Invalid');
})
function phonenumber(inputtxt) {
var phoneno = /^\d{10}$/;
if (inputtxt.match(phoneno)) {
return true;
} else {
alert("Not a valid Phone Number");
return false;
}
}
<input type="text" id="in" />
<button id="create_account">Create Account</button>
关于javascript - 使用 javascript 进行电话验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512368/