有一个脚本可以检查是否在间隙中输入了单词:
var check = function(input, word) {
input.keyup(function(){
if($(this).val() == word) {
$(this).css({'color':'green', 'border-bottom-color':'green'});
}
else {
$(this).css({'color':'black', 'border-bottom-color':'gray'});
}
});
input.blur(function(){
if($(this).val() == word) {
$(this).css({'color':'green', 'border-bottom-color':'green'});
}
else {
$(this).css({'color':'red', 'border-bottom-color':'red'});
}
});
}
check($('#am'), 'am');
check($('#has'), 'has');
check($('#will'), 'will');
input {
border: none;
border-bottom: 1px solid gray;
width: 50px;
outline: none;
text-align: center;
}
I <input type="text" id="am" /> a student.<br />
She <input type="text" id="has" /> a dog.<br />
We <input type="text" id="will" /> come home tomorrow.
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
它有两个问题。
第一:有没有可能以某种方式结合keyup和blur?很明显有一个.on('keyup blur', function(){}) 构造,但是else中有不同的颜色。
第二:对于每次检查,您需要使用自己的参数调用检查函数。现在有 3 个,但将有 33 个甚至更多。有没有办法优化这个?
很明显,您可以创建两个数组 - 带有输入和单词 - 并在循环中运行函数调用,在每次迭代时替换数组的相应元素。但我认为这个解决方案并不比目前的解决方案更好。有一些完全不同的选择吗?
2 个回答