我正在尝试从下拉列表中获取值。我有下拉列表,我有我想要的值,但我不知道如何将它们相互链接。所以类别的值应该在下拉列表中,然后该字符串中的图像值应该是结果...
这是名为ill.json的json文件数组
...
[{"id":"7","category":"Lente collectie 2021","image":"Teddy_bears_10.png"},{"id":"11","category":"Lente collectie 2021","image":"Individual_floral_elements_01.png"}
...
类别值进入下拉列表,然后结果应该是图像值:这是我的下拉列表...
const req = new XMLHttpRequest();
req.open('GET', 'ill.json', true);
req.send();
req.onload = function() {
const json = JSON.parse(req.responseText);
let dropdown = "";
let html = "";
//FILLING DROPDOWN WITH CATEGORYs
var result = json.reduce(function (r, a) {
r[a.category] = r[a.category] || [];
r[a.category].push(a);
return r;
}, Object.create(null));
let keys = Object.keys(result)
keys.forEach((key) => {
dropdown += "<select id='select'>"
dropdown += "<option value='" + key + "'>"
dropdown += key
dropdown += "</option>"
dropdown += "</select"
})
document.getElementsByClassName('dropdown')[0].innerHTML = dropdown;
...
我就是这样得到这些图像的...
//get all images
json.forEach(function(val) {
html += "<div class='illustratie-item'>";
html += "<img class='dt-filelist-image' src='" + val.image + "'/>"
html += "</div><br>";
});
document.getElementsByClassName('illustratie-wrapper')[0].innerHTML = html;
...
如果我说对了,应该就这么简单了:
var categorySelect = document.querySelector('.dropdown');
categorySelect.addEventListener('change', function(evt) {
var item = json.find(function(item) {
item.id === evt.target.value;
});
console.log(item.image); // there's your image
});