JavaScript数组被过滤,但选择选项不过滤重复id ?



我有两个具有拖放功能的数据表。数据表的每一行都包含id。当我将表1的行拖到表2中时。存储在数组中的数据。我有addArray函数,用于将id推入数组中,还过滤重复的id,并使其成为uniqueArray。现在我想创建包含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>

我看不到更新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;
}

最新更新