循环 2 个选择选项并显示 API 最佳匹配
Posted
技术标签:
【中文标题】循环 2 个选择选项并显示 API 最佳匹配【英文标题】:Loop through 2 select options and show API best match 【发布时间】:2021-11-21 00:17:46 【问题描述】:我想从我的 2 个选择选项中展示(“植物”的)最佳结果:“阳光”和“水”。 API console.log 在代码中:https://jsfiddle.net/Luckzzz/1p8bk0g5/
我想根据这 2 个选择选项的组合显示植物..
const url = 'https://front-br-challenges.web.app/api/v2/green-thumb/?sun=high&water=regularly&pets=false';
let sunlight = $('#sunlight');
sunlight.empty();
sunlight.append('<option selected="true" disabled>Choose sunlight</option>');
sunlight.prop('selectedIndex', 0);
let water = $('#water');
water.empty();
water.append('<option selected="true" disabled>Choose water amount</option>');
water.prop('selectedIndex', 0);
$.getJSON(url, function (data)
console.log(data);
$.each(data, function (key, entry)
// Populate SUNLIGHT dropdown:
sunlight.append($('<option></option>')
.attr('value', entry.abbreviation)
.text(entry.sun));
// Populate WATER dropdown:
water.append($('<option></option>')
.attr('value', entry.abbreviation)
.text(entry.water));
)
);
【问题讨论】:
【参考方案1】:不确定我是否正确理解了您的问题。你可以查看这个fiddle。
const url = 'https://front-br-challenges.web.app/api/v2/green-thumb/?sun=high&water=regularly&pets=false';
let selectedSun, selectedWater, globalData = [];
let sunlight = $('#sunlight');
sunlight.empty();
sunlight.append('<option selected="true" disabled>Choose sunlight</option>');
sunlight.prop('selectedIndex', 0);
let water = $('#water');
water.empty();
water.append('<option selected="true" disabled>Choose water</option>');
water.prop('selectedIndex', 0);
sunlight.on('change', function()
selectedSun = this.value;
showImages();
);
water.on('change', function()
selectedWater = this.value;
showImages();
);
const showImages = () =>
$("#items").empty();
globalData.forEach(item =>
if (!selectedWater || (selectedWater && item.water === selectedWater) &&
(!selectedSun || (selectedSun && item.sun === selectedSun)))
let img = document.createElement('img');
img.src = item.url;
$("#items").append(img);
)
$.getJSON(url, function (data)
console.log(data);
globalData = data;
const sunlights = data.reduce((acc, curr) =>
if (!acc.includes(curr.sun)) acc.push(curr.sun)
return acc;
, []);
const waterTypes = data.reduce((acc, curr) =>
if (!acc.includes(curr.water)) acc.push(curr.water)
return acc;
, []);
$.each(sunlights, function (key, entry)
sunlight.append($('<option></option>')
.attr('value', entry)
.text(entry));
)
$.each(waterTypes, function (key, entry)
water.append($('<option></option>')
.attr('value', entry)
.text(entry));
)
);
简而言之,我:
减少了这两个列表,所以你没有重复 添加了在选择之一更改时显示图像的方法【讨论】:
这正是我想要的。。很遗憾我没有得到这份工作,但学习是最重要的 :) 谢谢哥们!采纳答案!祝你有美好的一天! 不客气!以上是关于循环 2 个选择选项并显示 API 最佳匹配的主要内容,如果未能解决你的问题,请参考以下文章