考慮正則表達式
你可以很容易地通過RegExp.test()
功能簡單的正則表達式實現這一點。
var colors = new RegExp('red|green|purple|...');
然後,只需調用test()
功能,這將表明是否有這些術語是你的字符串中發現,如下圖所示:
// Define an expression of words to check for
var colors = new RegExp('red|green');
// Check if any of the words is contained within your element
if(colors.test($('#plz-input').val()){
alert('Wrong Value ...');
} else {
alert('Right Value!');
}
就像看到下方的您的個人條款與管道分開
實施例
<input id='colors' onkeyup='checkForColors(this);' /> <span id='result'></span>
<script>
var result = document.querySelector('#result');
function checkForColors(element){
var colors = new RegExp('red|green');
result.innerText = colors.test(element.value) ? 'Incorrect!' : 'Correct!';
}
</script>
該代碼片段不正確。 – bPratik
你確定嗎?它返回'錯誤!'如果在元素中輸入紅色或綠色,則爲「正確!」。我使用'onkeydown'編輯它到'onkeyup',這可能是你之前注意到的。 –
你說得對。它做了一個booboo,直到我刷新。恢復我的upvote :) – bPratik