如何限制AJAX加载数据的Dropdown下拉菜单选项显示数量?
限制下拉菜单选项数量的实现方案
要限制下拉菜单的选项数量,只需在处理返回数据时控制添加到下拉菜单的选项条数即可,以下是两种简单的实现方式:
方式一:截取指定数量的数据后再遍历
直接对返回的response.data使用slice()方法截取前N条数据(示例为前10条),再进行遍历添加:
// 提前获取下拉菜单元素 const $teamDropDown = $('#teamDropDown'); $.ajax({ url: "https://free-nba.p.rapidapi.com/teams", method: "GET", dataType: "json", headers: { 'X-RapidAPI-Key': "f8bbeecee3mshd11af53a602b7fcp133f59jsn3b4ffb3f20df", 'X-RapidAPI-Host': "free-nba.p.rapidapi.com" } }).then((response) => { // 截取前10条数据,可根据需求修改数字 const limitedTeams = response.data.slice(0, 10); limitedTeams.forEach((teamObject) => { const teamName = teamObject.full_name; const htmlToAppend = `<option value="${teamName}">${teamName}</option>`; $teamDropDown.append(htmlToAppend); }); });
方式二:遍历过程中判断索引
在forEach遍历的时候,通过索引判断,只添加前N条选项:
const $teamDropDown = $('#teamDropDown'); $.ajax({ url: "https://free-nba.p.rapidapi.com/teams", method: "GET", dataType: "json", headers: { 'X-RapidAPI-Key': "f8bbeecee3mshd11af53a602b7fcp133f59jsn3b4ffb3f20df", 'X-RapidAPI-Host': "free-nba.p.rapidapi.com" } }).then((response) => { response.data.forEach((teamObject, index) => { // 只添加前10条,索引从0开始,所以判断index < 10 if (index < 10) { const teamName = teamObject.full_name; const htmlToAppend = `<option value="${teamName}">${teamName}</option>`; $teamDropDown.append(htmlToAppend); } }); });
补充说明
- 代码中的
10可以根据你的需求修改为任意想要限制的数量 - 注意提前获取
$teamDropDown元素,避免出现未定义的问题
内容的提问来源于stack exchange,提问作者user19703227
相关产品推荐
相关产品推荐

