如何根据选择选项更新使用insertAdjacentHTML方法创建的HTML?

huangapple go评论55阅读模式
英文:

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(&#39;.container&#39;);
const sort= document.querySelector(&#39;.sort&#39;);
let url = &#39;https://mocki.io/v1/11356aa2-6371-41d4-9d49-77a5e9e9924f&#39;;
function getTours(option = false) {
fetch(url)
.then(res =&gt; res.json())
.then(out =&gt; {
switch(option) {
case &#39;durasc&#39;:
out.sort((a,b) =&gt; a.length - b.length)
break;
case &#39;durdesc&#39;:
out.sort((a,b) =&gt; b.length - a.length)
break;
case &#39;prasc&#39;:
console.log(&quot;Lowest price first&quot;);
break;
case &#39;prdesc&#39;:
console.log(&quot;Highest price first&quot;);
break;
default:
out;
console.log(option);
}
console.log(out);
out.forEach((el,i) =&gt; {
const cities = el.cities;
const lastCity = cities.slice(-1)
const dates = el.dates.map(d =&gt; d.start);
let availableSpaces = el.dates.map(d =&gt; d.availability);
const fromPrice = dates.length!==0 ? Math.min(...el.dates.map(item =&gt; item.eur)) : 0;
const month = [&quot;JAN&quot;, &quot;FEB&quot;, &quot;MAR&quot;, &quot;APR&quot;, &quot;MAY&quot;, &quot;JUN&quot;, &quot;JUL&quot;, &quot;AUG&quot;, &quot;SEPT&quot;, &quot;OCT&quot;, &quot;NOV&quot;, &quot;DEC&quot;];
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 = [&#39;No&#39;, &#39;No&#39;];
return &#39;SOLD OUT!&#39;
}
}
let image = el.images.filter(img =&gt; img.is_primary===true);
image.length&gt;0 &amp;&amp; image[0].hasOwnProperty(&#39;url&#39;) &amp;&amp; image[0].url!==&#39;&#39; ? image = image[0].url : image = &quot;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&amp;w=0&amp;k=20&amp;c=PM_optEhHBTZkuJQLlCjLz-v3zzxp-1mpNQZsdjrbns=&quot;;
const operatorName = el.operator_name;
const html = `Here is my HTML text`;
container.insertAdjacentHTML(&#39;beforeend&#39;, html);
});
});
}
let listOne = document.getElementsByClassName(&#39;sort&#39;)
for (let i = 0; i &lt; listOne.length; i++) {
let option = listOne[i];
option.addEventListener(&#39;change&#39;, () =&gt; {
getTours(option.value);
return option.value;
})
}
getTours();

<!-- end snippet -->

答案1

得分: 1

如果我理解正确,您想要:

  1. 检索数据
  2. 基于选项进行排序
  3. 显示排序后的数据

步骤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:

  1. retrieve data
  2. sort based on option
  3. 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 = &#39;&#39;

// 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(&#39;ul&#39;)
const addElements = () =&gt; {
sorted.forEach(e =&gt; {
let html = `&lt;li&gt;${e}&lt;/li&gt;`
cont.insertAdjacentHTML(&#39;beforeend&#39;, html)
})
}
const addElementsClean = () =&gt; {
cont.innerHTML = &#39;&#39;;
addElements();
}

<!-- language: lang-html -->

&lt;button onclick=&#39;addElements()&#39;&gt;add w/o clean&lt;/button&gt;
&lt;button onclick=&#39;addElementsClean()&#39;&gt;add clean&lt;/button&gt;
&lt;ul&gt;
&lt;li&gt;dummy&lt;/li&gt;
&lt;li&gt;elements&lt;/li&gt;
&lt;/ul&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月9日 18:39:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定