英文:
How to update HTML created with insertAdjacentHTML method based on a select option?
问题
以下是代码部分的翻译:
const container = document.querySelector('.container');
const sort = document.querySelector('.sort');
let url = 'https://mocki.io/v1/11356aa2-6371-41d4-9d49-77a5e9e9924f';
function getTours(option = false) {
fetch(url)
.then(res => res.json())
.then(out => {
switch(option) {
case 'durasc':
out.sort((a, b) => a.length - b.length)
break;
case 'durdesc':
out.sort((a, b) => b.length - a.length)
break;
case 'prasc':
console.log("Lowest price first");
break;
case 'prdesc':
console.log("Highest price first");
break;
default:
out;
console.log(option);
}
console.log(out);
out.forEach((el, i) => {
const cities = el.cities;
const lastCity = cities.slice(-1)
const dates = el.dates.map(d => d.start);
let availableSpaces = el.dates.map(d => d.availability);
const fromPrice = dates.length !== 0 ? Math.min(...el.dates.map(item => item.eur)) : 0;
const month = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEPT", "OCT", "NOV", "DEC"];
const getDate = function (date) {
if (date !== undefined) {
const d = new Date(date)
const day = d.getDate();
const name = month[d.getMonth()]
const year = d.getFullYear()
const fullDate = `${day} ${name} ${year}`;
return fullDate;
} else {
availableSpaces = ['No', 'No'];
return 'SOLD OUT!';
}
}
let image = el.images.filter(img => img.is_primary === true);
image.length > 0 && image[0].hasOwnProperty('url') && image[0].url !== '' ? image = image[0].url : image = "https://media.istockphoto.com/id/1357365823/vector/default-image-icon-vector-missing-picture-page-for-website-design-or-mobile-app-no-photo.jpg?s=612x612&w=0&k=20&c=PM_optEhHBTZkuJQLlCjLz-v3zzxp-1mpNQZsdjrbns=";
const operatorName = el.operator_name;
const html = `这是我的HTML文本`;
container.insertAdjacentHTML('beforeend', html);
});
});
}
let listOne = document.getElementsByClassName('sort')
for (let i = 0; i < listOne.length; i++) {
let option = listOne[i];
option.addEventListener('change', () => {
getTours(option.value);
return option.value;
})
}
getTours();
请注意,代码中的HTML文本是"这是我的HTML文本",你可以根据需要将其替换为实际的HTML内容。
英文:
I am fetching data and then creating an HTML content which is displayed at page start.
I have a select dropdown list with different options that would then sort the array of objects from the API and should then update the HTML content with the new order. Right now I'm getting the sorted array correctly but the HTML content is just being added after the already existing one.
What am I missing or doing wrong?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const container = document.querySelector('.container');
const sort= document.querySelector('.sort');
let url = 'https://mocki.io/v1/11356aa2-6371-41d4-9d49-77a5e9e9924f';
function getTours(option = false) {
fetch(url)
.then(res => res.json())
.then(out => {
switch(option) {
case 'durasc':
out.sort((a,b) => a.length - b.length)
break;
case 'durdesc':
out.sort((a,b) => b.length - a.length)
break;
case 'prasc':
console.log("Lowest price first");
break;
case 'prdesc':
console.log("Highest price first");
break;
default:
out;
console.log(option);
}
console.log(out);
out.forEach((el,i) => {
const cities = el.cities;
const lastCity = cities.slice(-1)
const dates = el.dates.map(d => d.start);
let availableSpaces = el.dates.map(d => d.availability);
const fromPrice = dates.length!==0 ? Math.min(...el.dates.map(item => item.eur)) : 0;
const month = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEPT", "OCT", "NOV", "DEC"];
const getDate = function (date) {
if (date!==undefined) {
const d = new Date(date)
const day = d.getDate();
const name = month[d.getMonth()]
const year = d.getFullYear()
const fullDate = `${day} ${name} ${year}`;
return fullDate;
} else {
availableSpaces = ['No', 'No'];
return 'SOLD OUT!'
}
}
let image = el.images.filter(img => img.is_primary===true);
image.length>0 && image[0].hasOwnProperty('url') && image[0].url!=='' ? image = image[0].url : image = "https://media.istockphoto.com/id/1357365823/vector/default-image-icon-vector-missing-picture-page-for-website-design-or-mobile-app-no-photo.jpg?s=612x612&w=0&k=20&c=PM_optEhHBTZkuJQLlCjLz-v3zzxp-1mpNQZsdjrbns=";
const operatorName = el.operator_name;
const html = `Here is my HTML text`;
container.insertAdjacentHTML('beforeend', html);
});
});
}
let listOne = document.getElementsByClassName('sort')
for (let i = 0; i < listOne.length; i++) {
let option = listOne[i];
option.addEventListener('change', () => {
getTours(option.value);
return option.value;
})
}
getTours();
<!-- end snippet -->
答案1
得分: 1
如果我理解正确,您想要:
- 检索数据
- 基于选项进行排序
- 显示排序后的数据
步骤1和2似乎已经实现,但新排序的数据被附加到已经存在的数据中?
如果是这种情况,您似乎从未清除container
元素。
重要提示:我通常犯的一个错误是输入 X innerHtml
而不是 innerHTML
<- 所有字母大写
console.log(out) // 大约在第26行
// 清空容器
container.innerHTML = '';
// 您的 `out.foreach` 循环
我已经包含了一个代码片段,以显示这个更改会产生什么效果,希望这是您所寻找的!
<!-- 开始代码片段:js 隐藏:false 控制台:true babel:false -->
<!-- 语言:lang-js -->
const sorted = [1,2,3,4]
const cont = document.querySelector('ul')
const addElements = () => {
sorted.forEach(e => {
let html = `<li>${e}</li>`
cont.insertAdjacentHTML('beforeend', html)
})
}
const addElementsClean = () => {
cont.innerHTML = '';
addElements();
}
<!-- 语言:lang-html -->
<button onclick='addElements()'>添加(不清空)</button>
<button onclick='addElementsClean()'>添加并清空</button>
<ul>
<li>dummy</li>
<li>elements</li>
</ul>
<!-- 结束代码片段 -->
希望这对您有所帮助!
英文:
If i understand correctly you want to:
- retrieve data
- sort based on option
- display sorted data
Step 1 and 2 seem to work but your newly sorted data get's appended to the already existing data?
If that is the case, you never seem to clear your container
element.
IMPORTANT a mistake I usually make is typing X innerHtml
instead of innerHTML
<- all caps
console.log(out) // line 26-ish
// clear the container
container.innerHTML = ''
// your out.foreach loop
I've included a snippet to show what the change would do, hopefully it's what you're looking for!
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const sorted = [1,2,3,4]
const cont = document.querySelector('ul')
const addElements = () => {
sorted.forEach(e => {
let html = `<li>${e}</li>`
cont.insertAdjacentHTML('beforeend', html)
})
}
const addElementsClean = () => {
cont.innerHTML = '';
addElements();
}
<!-- language: lang-html -->
<button onclick='addElements()'>add w/o clean</button>
<button onclick='addElementsClean()'>add clean</button>
<ul>
<li>dummy</li>
<li>elements</li>
</ul>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论