gpt4 book ai didi

javascript - 无限滚动选择2组

转载 作者:行者123 更新时间:2023-12-03 00:13:16 25 4
gpt4 key购买 nike

我正在使用带有无限滚动的select2组选项,并且数据是通过Ajax调用每页10来的。这里出现了一些问题,假设用户1有15个数据,用户2有15个数据,首先10个数据来自用户1 和下一页 10(用户 1 的 5 个数据和用户 2 的 5 个数据)。数据获取没有问题,但问题是用户 1 组显示双倍。如何防止我的 select2 选项组双重显示?有什么办法可以重新创建一个选项组吗?

HTML 代码

<div class="container">
<form id="frm">
<h1>Solution 1</h1>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="tagInput">Get data by ajax calling</label>
<select class="form-control" id="pictures_tag_input">
</select>
<small class="form-text text-muted"><p class="text-info">Infinite Scroll</p></small>
</div>
</div>
</div>
</form>
</div>

JS 代码

$(document).ready(function() {
// solution 1
//example.com/articles?page[number]=3&page[size]=1
http: $("#pictures_tag_input").select2({
placeholder: "Search for options",
ajax: {
url: "https://jsonplaceholder.typicode.com/users/1/todos",
dataType: "json",
global: false,
cache: true,
delay: 250,
minimumInputLength: 2,
data: function(params) {
// console.log(params.page || 1);
return {
q: params.term, // search term
_page: params.page || 1,
_limit: 10 // page size
};
},
processResults: function(data, params) {
params.page = params.page || 1;
var datx = getNestedChildren(data);
// console.log(datx);

return {
results: datx,
pagination: {
more: true
}
};
} //end of process results
} // end of ajax
});

function getNestedChildren(list) {
var roots = [];
for (i = 0; i < list.length; i += 1) {
node = list[i];

if (roots.length === 0) {
var obj = {
text: "User " + node.userId,
children: [{ id: node.id, text: node.title }]
};
roots.push(obj);
} else {
var obj = {
text: "User " + node.userId,
children: [{ id: node.id, text: node.title }]
};
var rootArray = $.map(roots, function(val, i) {
var vl = "User " + node.userId;
if (val.text === vl) return val;
else return undefined;
});
if (rootArray.length > 0) {
var obj1 = {
id: node.id,
text: node.title
};
rootArray[0].children.push(obj1);
} else {
roots.push(obj);
}
}
}
return roots;
}
});

enter image description here

Demo https://codepen.io/mdshohelrana/pen/MLVZEG

最佳答案

尝试使用以下代码

templateResult: function(data) {
if (typeof data.children != 'undefined') {
$(".select2-results__group").each(function() {
if (data.text == $(this).text()) {
return data.text = '';
}
});
}
return data.text;
}

注意:需要从服务器端进行分组,否则您必须从客户端创建主详细信息。

关于javascript - 无限滚动选择2组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54628556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com