我有一个输入框,我想要根据您输入的文本发出特定警报。当我输入“hello”以外的内容时,我不断收到错误“TypeError: input.match(...) is null” .
我的代码:
<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>
最佳答案
来自 Mozilla 开发者网络文档 String.prototype.match() :
“包含整个匹配结果和任何括号捕获的匹配结果的数组;如果没有匹配,则为 null。”
input.match(/hello/g)
返回 null。然后您将在 null
上调用 length
。 null
没有可以调用的函数。
我建议你尝试一下:
if (input.match(/hello/g) == null) {
// No Matches
alert("bye");
} else {
// Matches
alert("hello");
}
关于javascript - 为什么我得到 "TypeError: input.match(...) is null"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41432617/