[英]Compare the values of array in javascript
我有两个复选框,A和B,当它们中的任何一个都被单击时,都应触发该事件。 我需要跟踪数组中的检查值。
可能的值。
[eA,eB] -> if both are checked.
[] -> if A and B are unchecked.
[eA] -> if A is checked and also if B is unchecked.
[eB] -> if B is checked and also if A is unchecked.
我尝试过这样的事情
var all = new Array();
getValues = function(e) {
for (i = 0; i < e.length; i++) {
all[i] = e[i];
if (e[i] == "eB") {
refreshFlag = true;
}
}
if (e.length == 0) {
//need to check whether eB was checked before and set the flag
}
if (e.length == 1) {
//need to check whether eB was checked before and set the flag
}
}
我怎样才能做到这一点?
我包括了jQuery,但以下是您需要执行的操作的示例:
$(document).ready(function() { var outputArr = []; $('input[type="checkbox"]').click(function(e) { var val = $(this).val(); var index = outputArr.indexOf(val); if (index === -1) { outputArr.push(val); } else { outputArr.splice(index, 1); } $('#output').val(JSON.stringify(outputArr)); }); });
<!DOCTYPE html> <html> <head> <style>label { display: block; }</style> <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> </head> <body> <form id="form"> <label><input type="checkbox" value="eA" /> Checkbox A</label> <label><input type="checkbox" value="eB" /> Checkbox B</label> </form> <textarea id="output" disabled>[]</textarea> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.