javascript - jquery 从数组选择选项 - 重复项

标签 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 中的选择字段中,并且我希望它们是唯一的。

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

是否有一种方法可以显示一个 x 以及所有将 x 作为 #from 的 #to 值?

最佳答案

你可以尝试这样的事情:

 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) );
    }
  }

关于javascript - jquery 从数组选择选项 - 重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42510341/

相关文章:

php - 如何内爆 $_SESSION ARRAY 然后插入 Mysql

java - 为什么这不会返回该区域?

c - 如何连接指针数组?

javascript - 从 JSON.stringify 中提取数据

javascript - jQuery .remove() 上的 IE7/IE8 Javascript 错误

php - 使用ajax和jquery将数据插入数据库

jquery - 使用 jQuery 延迟更改 CSS 属性

javascript - 字符串数组因意外 token javascript 引发错误

javascript - 使用 MongoDB $setEquals 时引号中的 ID

javascript - 使用 div 时出现错误appendTo()