【发布时间】:2019-11-24 13:34:56
【问题描述】:
我希望在输入“hello”、“Hello”、“HELLO”等时为文本着色
<input id="input" type="input" value="hello"/>
<span id="result">Hello</span>
<script>
var input = document.getElementById('input');
var result = document.getElementById('result');
function greenTheTitle(){
result.style.color = 'green';
}
function redTheTitle(){
result.style.color = 'red';
}
input.addEventListener('keyup', function goodMrn(){
var inputValue = input.value;
if(inputValue == /hello/i ){ //does'nt work here
greenTheTitle();
}
if(inputValue != /hello/i ){ //and here
redTheTitle();
}});
</script>
</body>
</html>
if(inputValue == "hello" ) 有效
但
if(inputValue == /hello/i ) 没有
【问题讨论】:
-
字符串不是正则表达式,所以你不能像那样使用
==运算符 -
你很可能想要像
/hello/i.test(inputValue)这样的东西 -
谢谢迪恩·泰勒,它有效:)
标签: javascript regex