Javascript 为什么我会得到;TypeError:input.match(…)为null;?
我有一个输入框,我希望根据您键入的文本发出特定警报。当我键入除“hello”之外的内容时,我不断收到错误“TypeError:input.match(…)为null” 我的代码:Javascript 为什么我会得到;TypeError:input.match(…)为null;?,javascript,html,error-handling,Javascript,Html,Error Handling,我有一个输入框,我希望根据您键入的文本发出特定警报。当我键入除“hello”之外的内容时,我不断收到错误“TypeError:input.match(…)为null” 我的代码: <html> <body> <form name="form5"> <input type=text size=51 name="input"> <input onClick=auswert() type=button value="submit"&g
<html>
<body>
<form name="form5">
<input type=text size=51 name="input">
<input onClick=auswert() type=button value="submit">
</form>
<script type="text/javascript">
function auswert() {
var input = document.form5.input.value;
if (input.match(/hello/g).length == 1) alert("hello");
else alert("bye");
}
</script>
</body>
</html>
函数auswert(){
var输入=document.form5.input.value;
if(input.match(/hello/g).length==1)警报(“hello”);
其他警报(“再见”);
}
来自Mozilla开发者网络文档:
“包含整个匹配结果和任何括号的数组捕获匹配结果;如果没有匹配项,则为null。”
input.match(/hello/g)
返回null。然后在null
上调用length
null
没有可以对其调用的函数
我建议你试试:
if (input.match(/hello/g) == null) {
// No Matches
alert("bye");
} else {
// Matches
alert("hello");
}
来自Mozilla开发者网络文档: “包含整个匹配结果和任何括号的数组捕获匹配结果;如果没有匹配项,则为null。”
input.match(/hello/g)
返回null。然后在null
上调用length
null
没有可以对其调用的函数
我建议你试试:
if (input.match(/hello/g) == null) {
// No Matches
alert("bye");
} else {
// Matches
alert("hello");
}
因为如果没有匹配项,
input.match(/hello/g)
返回null
。阅读文档总是很有用的。如果不想阅读文档,可以编写更好的逻辑if((input.match(/hello/g))&&(input.match(/hello/g).length==1))
将.match()
的结果分配给一个变量要比执行两次匹配工作好得多,因为这可能需要大量CPU。或者,未经测试,if((input.match(/hello/g)| |[]).length==1){…
,因为input.match(/hello/g)
如果不匹配,则返回null
。阅读文档总是很有用的。如果不想阅读文档,可以编写更好的逻辑if((input.match(/hello/g))&&(input.match(/hello/g).length==1))
将.match()
的结果分配给一个变量要比执行两次匹配工作好得多,因为这可能需要大量CPU。或者,未经测试,if((input.match(/hello/g)| |[]).length==1){…