【问题标题】:JavaScript Array is filtered but select option are not filtered duplicate IDs?JavaScript 数组被过滤但选择选项没有被过滤重复 ID?
【发布时间】:2021-04-21 06:20:32
【问题描述】:

我有两个具有拖放功能的数据表。每行数据表都包含 ID。当我将表 1 的行拖到表 2 中时。存储到数组中的数据。我有用于将 ID 推送到数组中的 addArray 函数,还可以过滤重复的 ID 并使其成为唯一数组。现在我想创建包含 iD 作为值的选择选项元素。我希望在拖放时重新创建选择选项。如果有任何帮助,我将不胜感激。

JS

$(document).ready(function () {
    new Sortable(drag, {
        group: 'sortables',
        onChange: function (e, tr) {
            addArray();
        },
    });

    new Sortable(drop, {
        group: "sortables",
        onChange: function (event, tr) {
            addArray();
        },
    });

    function addArray() {
        let articles = [];

        $('#drop').children().each(function () {
            articles.push($(this).data('pk'))
        });
        let uniqueArray = articles.filter((item, index, array) => { // filter Duplicate ID
            return array.indexOf(item) === index
        })
        $.each(uniqueArray, function (index, value) { // Create Option Element using Each ID form Array
            $('#id_articles').append($('<option/>', { value: value, selected: '' }));
        });
        console.log(uniqueArray)
    };
});

输出

<select name="articles" id="id_articles" multiple="" style="display: none;">
    <option value="67" selected="selected"></option>
    <option value="66" selected="selected"></option>
    <option value="67" selected="selected"></option>
    <option value="67" selected="selected"></option>
    <option value="66" selected="selected"></option>
    <option value="66" selected="selected"></option>
    <option value="67" selected="selected"></option>
    <option value="67" selected="selected"></option>
    <option value="66" selected="selected"></option>
</select>

【问题讨论】:

  • console.log(uniqueArray);的输出是什么
  • 输出是过滤器 ["67", "66"] 作为我想要做的,但在 html 选择选项包含重复值

标签: javascript html jquery bootstrap-4


【解决方案1】:

我看不到更新articles 数组的目的,然后将其过滤为uniqueArray,而您可以使用一个简单的函数在第一个.each() 中更新两个数组以防止重复值.. 尝试下一个代码它应该工作

function addArray() {
   let articles = uniqueArray = [];
   $('#drop').children().each(function () {
      articles.push($(this).data('pk'));
      uniqueArray = stop_duplicate_in_array(uniqueArray , $(this).data('pk'));
   });
   console.log(uniqueArray)
   let options = '';
   $.each(uniqueArray, function (index, value) { // Create Option Element using Each ID form Array
     options += `<option value="${value}" selected="">${value}</option>`;
   }); 
   $('#id_articles').html(options);   
}
function stop_duplicate_in_array(array , value){
   var index = array.indexOf(value);
   if(index > -1){array.splice(index, 1);}
   array.push(value);
   return array;
}

【讨论】:

  • console.log 中的过滤器 ["67", "66"] 是我想要做的,但在包含重复选项的 html #id_articles 中,我想删除重复的选项
  • @afi 答案已更新,请检查.. 您可以使用options html 而不是附加,然后使用.html() 而不是.append()
猜你喜欢
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多