javascript - 使用附加子项时的较短方法
问题描述
我正在从通过 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>
解决方案
由于您要分配给.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,然后在创建结构后安全地插入它们。例如,你可以使用createElement
for.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;
这将是一种更安全的方法。
推荐阅读
- symfony - 在 Symfony 4 的 ExceptionListener 中访问记录器
- linux - 如何将命令的连续输出重定向到用c编写的程序的输入
- windows - 您如何在 golang 中获取 Windows 上的硬盘数量(不是分区!)?
- c - 为什么这个“C”代码的输出是这样的?
- erlang - Ejabberd 服务器处理器过载(CPU Overload)
- unit-testing - 在烧瓶中测试“POST”和“GET”方法
- javascript - JavaScript 中括号的使用
- dependency-injection - 使用 Jersey 2 (HK2) DI 注册 Dropwizard 配置
- javascript - 在 AngularJS 中创建模态窗口
- java - 事件溯源“UNDO”流程中的乐观锁机制