在此代码中," ans"的变量值我是否根据模式输入了值总是假的。我无法理解原因。
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+@[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);

<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
&#13;
答案 0 :(得分:1)
您在提交按钮事件中使用了名为validate
的函数,但未对其进行定义。定义validate
函数后,一切正常。
function validate() {
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+@[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
答案 1 :(得分:1)
试试这个
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
<script>
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+@[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
</script>
答案 2 :(得分:1)
您应该将所有代码移动到已定义的函数validate()
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+@[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}