复选框和表单提交与onChange方法Javascript不兼容

时间:2015-05-12 20:56:21

标签: javascript html methods onchange

我的脚本中有一个字符串数组,我有两个函数,一个按最大和最小长度过滤字符串,一个方法根据它们的字符排除一些字符串。这两种方法不能很好地协同工作,当我取消选中它们时,它们不会显示相应的数组。

这是我的代码:

<div id="demo"> </div>
<div class="item">
  <form id="aForm" onchange="filter()">
    <input type="checkbox" id="A" value="A">Exclude words with 'A'
    <br>
    <input type="checkbox" id="E" value="E">Exclude words with 'E'
    <br>
    <input type="checkbox" id="O" value="O">Exclude words with 'O'
    <br>
  </form>
</div>
<div class="item" id="length">
  <form id="oForm">
    <input type="text" name="minLength" size="2" />Minimum Lenght
    <br>
    <input type="text" name="maxLength" size="2" />Maximum Length
    <br>
    <input type="button" value="Update" onclick="updateLength()">
  </form>
</div>

在这里,我有我的脚本:

 <script type="text/javascript">
  var animals = ["Bear", "Mouse", "Cat", "Tiger", "Lion"];

  function filter() {
    var a = document.getElementById('A').checked,
      e = document.getElementById('E').checked,
      o = document.getElementById('O').checked,
      result2; //make a copy

    var copy2 = document.getElementById("demo").innerHTML;
    var array = copy2.split(" ");

    result2 = array.filter(function(value) {
      value = value.toLowerCase();
      return (!a || value.indexOf('a') == -1) && (!e || value.indexOf('e') == -1) && (!o || value.indexOf('o') == -1);
    })
    document.getElementById("demo").innerHTML = result2;
  }
  filter();

  function updateLength() {
    minLength = oForm.elements["minLength"].value;
    maxLength = oForm.elements["maxLength"].value;
    var result = [];
    var copy2 = document.getElementById("demo").innerHTML;
    var array = copy2.split(" ");
    for (var i in array) {

      if (minLength <= array[i].length && array[i].length <= maxLength) {
        result += " " + array[i];
      }
      document.getElementById("demo").innerHTML = result;
    }
  }
  updateLength();
</script>

1 个答案:

答案 0 :(得分:0)

updateLength()函数放在filter()函数之外,并将onchange侦听器放在所有输入上,而不是表单上。表单本身的状态不会改变,输入是。