比较javascript中的数组值

时间:2015-08-13 13:00:57

标签: 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
    }
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我包含了jQuery,但这里有一个你需要做的例子:

&#13;
&#13;
$(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));
  });
});
&#13;
<!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>
&#13;
&#13;
&#13;