从数组中jquery来选择选项 - 重复

时间:2017-02-28 13:40:38

标签: javascript jquery arrays append

我有这个HTML表单:

<form id="form">
  <select name="from" id="from" class="form-control">
      <option value=""></option>
  </select>

  <select name="to" id="to" class="form-control">
    <option value=""></option>
  </select>

  <button type="button" id="but">Click Me!</button>
</form>

点击按钮,我运行这个jquery脚本

$( document ).ready(function() {
  var from = $('#from').val();
  var to = $('#to').val();


  //Object 1
  var obj1 = {
    from: "x", to: "y"
  };

  //Object 2
  var obj2 = {
    from: "x", to: "z"
  };

  //Object 3
  var obj3 = {
    from: "y", to: "z"
  };

  //Array
  var a=[];
  //Put objects in array
  a.push(obj1, obj2, obj3);

  for (i = 0; i < a.length; ++i){
    if (a[i].from) {

        // Inserts two x's
        $('#from').append( $('<option></option>').val(a[i].from).html(a[i].from) );
    }
  }


  //On click
  $('#but').on('click', function(e){
    var from = $('#from').val();
    for (i = 0; i < a.length; ++i) {
      if (from == a[i].from) {

          //Update once the #to values
          $('#to').append( $('<option></option>').val(a[i].to).html(a[i].to) );
      }
    }
  });
});

我的问题是我试图将数组值作为选项放在html的select字段中,我希望它们是唯一的。

前两个选项是:从x到y和从x到z,它在#from值中返回两个x。

有没有办法显示一个x和所有#to值,其中x为#from?

2 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情:

 var a = [];
 var fromExists = [];

  a.push(obj1, obj2, obj3);

  for (i = 0; i < a.length; ++i){
    if (a[i].from && fromExists.indexOf(a[i].from) === -1) {
        fromExists.push(a[i].from);

        // Inserts two x's
        $('#from').append( $('<option></option>').val(a[i].from).html(a[i].from) );
    }
  }

答案 1 :(得分:1)

或尝试这个:)使用选项类

for (i = 0; i < a.length; ++i){
    if (a[i].from) {
        if($('#from').find('option[value="'+a[i].from+'"]').length == 0) {
            $('#from').append(new Option(a[i].from, a[i].from));
        }
    }
  }