首页 > 解决方案 > 使用附加子项时的较短方法

问题描述

我正在从通过 fetch 请求返回的对象创建一些元素,并想知道是否有更好的方法来简化这一点?

就目前而言,它按预期工作,但对于看似简单的任务来说,它似乎太长了?

async function getJobs() {

  const response = await fetch('https://app.beapplied.com/public/all-jobs');
  const data = await response.json();
  console.log(data.jobs);
  for (const job of data.jobs) {
    const jobContainer = document.getElementById("jobData");

    const jobListing = document.createElement('li');
    jobContainer.appendChild(jobListing);
    jobListing.setAttribute('class', 'whr-item')

    const jobLink = document.createElement('a');
    jobListing.appendChild(jobLink);
    jobLink.setAttribute('href', job.applyLink)

    let jobTitle = document.createElement("h3");
    jobTitle.innerHTML = job.title;
    jobTitle.setAttribute('class', 'whr-title')
    jobLink.appendChild(jobTitle);

    const jobInfo = document.createElement('ul');
    jobListing.appendChild(jobInfo);
    jobInfo.setAttribute('class', 'whr-info')

    let jobTeam = document.createElement("li");
    jobTeam.innerHTML = job.team;
    jobTeam.setAttribute('class', 'whr-dept')
    jobInfo.appendChild(jobTeam);

    let jobLocation = document.createElement("li");
    jobLocation.innerHTML = job.location
    jobLocation.setAttribute('class', 'whr-location')
    jobInfo.appendChild(jobLocation);
  }
}

getJobs()
<ul id="jobData" class="whr-items"></ul>

标签: javascripthtmlfetchappendchild

解决方案


由于您要分配给.innerHTML嵌套子级的 ,因此写出 HTML 字符串并进行插值将是等效的,并且一目了然:

const jobContainer = document.getElementById("jobData");
for (const job of data.jobs) {
    jobContainer.insertAdjacentHTML(
        'beforeend',
        `<li class="whr-item">
          <a href="${job.applyLink}">
            <h3>${job.title}</h3>
          </a>
          <ul>
            <li class="whr-dept">${job.team}</li>
            <li class="whr-location">${job.location}</li>
          </ul>
        </li>
        `
    );
}

也就是说,直接插入外部值 HTML(或使用.innerHTML外部值)是一种安全风险,因为它允许任意代码执行。我建议写出没有插入值的 HTML,然后在创建结构后安全地插入它们。例如,你可以使用createElementfor.whr-item所以你有一个对它的引用,插入它的没有动态值的 HTML,然后做

item.querySelector('a').href = job.applyLink;
item.querySelector('h3').href = job.title;
item.querySelector('.whr-dept').href = job.team;
item.querySelector('.whr-location').href = job.location;

这将是一种更安全的方法。


推荐阅读