2017-01-02 129 views
-1

我有一個輸入框,我想要根據輸入的文本輸入一個特定的警報。當我輸入除「hello」之外的東西時,我總是收到錯誤「TypeError:input.match(...)爲null」。爲什麼我會得到「TypeError:input.match(...)爲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> 
+1

因爲'input.match(/你好/ G)''返回null',如果沒有匹配。閱讀[documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match)總是有用的。 – Teemu

+0

或者如果您不想閱讀文檔,請創建一個更好的邏輯。 ((input.match(/ hello/g))&&(input.match(/ hello/g).length == 1) –

回答

0

從Mozilla開發網絡文檔String.prototype.match()

「;如果沒有匹配空含有整個匹配結果,並且任何一個Array括號捕獲匹配的結果。」

input.match(/hello/g)返回null。然後你在null上調用lengthnull沒有你可以調用的函數。

我建議你試試:

if (input.match(/hello/g) == null) { 
    // No Matches 
    alert("bye"); 
} else { 
    // Matches 
    alert("hello"); 
} 
相關問題