2016-08-26 38 views
1

我正在为用户填写答案编码测验,如果它与数组中的正确答案之一匹配,则该字段将变为绿色,否则变为红色。这是什么在起作用:如何将输入值与数组的整个范围匹配?

var arr = ["a", "b", "c"]; 
var id = document.getElementById("id"); 
if (id.value == arr[0] 
    || id.value == arr[1] 
    || id.value == arr[2] 
    || id.value == arr[3]){id.style.backgroundColor = "#83C183";} 
    else {id.style.backgroundColor = "#E06969";} 

但我想摆脱的:

if (id.value == arr[0] || id.value == arr[1] || id.value == arr[2] || id.value == arr[3]) 

我试着用for循环遍历数组:

var arr = ["a", "b", "c"]; 
var id = document.getElementById("id"); 
for (var i = 0; i < arr.length; i++){ 
     if (id.value == arr[i]){id.style.backgroundColor = "#83C183";} 
     else {id.style.backgroundColor = "#E06969";} 
     } 

但它只返回"c"这是真的。在这种情况下,如何选择阵列中的所有项目?

+0

增加了一个工作片段,以更清晰的代码[这里](http://stackoverflow.com/a/39158841/1409180) – nikjohn

+1

'bkgColor = arr.includes(id.value)? “绿色”:“红色” – Redu

回答

1

创建一个标志变量,只要它与数组中的某个项目匹配就设置该变量。然后检查该标志以确定是否将背景颜色设置为绿色或红色。

示例代码:

var arr = ["a", "b", "c"]; 
var id = document.getElementById("id"); 
var flag = false; 
for (var i = 0; i < arr.length; i++){ 
    if (id.value == arr[i]) 
    { 
     flag = true;   
     break; 
    } 
} 

if (flag) {id.style.backgroundColor = "#83C183";} 
else {id.style.backgroundColor = "#E06969";} 
+0

循环不是最干净的方法,当有像javascript'filter'功能的东西时IMO – nikjohn

+0

非常感谢你,结果非常好! – Andy

+0

A'break;'也会有所帮助。 –

1

您可以简单地使用indexOf的方法来检查,如果答案存在于阵列与否。

var arr = ["a", "b", "c"]; 
var id = document.getElementById("id"); 
if(arr.indexOf(id.value) > -1) 
id.style.backgroundColor = "#83C183"; 
else 
id.style.backgroundColor = "#E06969"; 
+0

检查出来了,没有为我工作:(但是thanx为你的努力 – Andy

0

一个实现这种更清洁的方式如下:

function evaluateAnswerFilter() { 
 
    var arr = ["a", "b", "c"]; 
 
    var inputEl = document.getElementById("id"); 
 
    var truth = arr.filter(function(option) { 
 
    return option === inputEl.value 
 
    }); 
 
    truth.length ? inputEl.style.backgroundColor = "#83C183" : 
 
    inputEl.style.backgroundColor = "#E06969" 
 
} 
 

 
function evaluateAnswerIncludes() { 
 
    var arr = ["a", "b", "c"]; 
 
    var inputEl = document.getElementById("id"); 
 
    arr.includes(inputEl.value) ? inputEl.style.backgroundColor = "#83C183" : 
 
    inputEl.style.backgroundColor = "#E06969" 
 
}
<body> 
 
    <input name="id" id="id" type="text" /> 
 
    <button onclick="evaluateAnswerFilter()">Evaluate with Filter</button> 
 
    <button onclick="evaluateAnswerIncludes()">Evaluate with Includes</button> 
 

 
</body>

+0

达斯汀,这个片断其实已经在函数中了,我只是懒得给所有图片,它会像函数里面的函数那样工作吗? – Andy

+0

我didn大多数函数都可以嵌套在JS的函数中 我的建议是在数组中使用'filter'函数,它比运行循环更清晰(这是因为性能不佳而臭名昭着)甚至更好,你可以使用像'Array.prototype.includes' – nikjohn

+0

刚刚检查出来,它没有在我的情况下工作 – Andy