我必须只使用普通的JS,没有jQuery或框架(这将使生活更容易)…这里是JS文件:
let candidates = [];
const getCandidates = () => {
axios.get('<a certain endpoint here, the endpoint is good, that is not the problem>')
.then((response) => {
for (let i = 0; i < response.data.candidates.length; i++) {
candidates.push(response.data.candidates[i]);
}
console.log(candidates);
return candidates;
})
};
getCandidates();
function setAttributes(el, attrs) {
for(let key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
function addCandidatesToHtml() {
let mainContainer = document.getElementById("candidatesGoHere");
for (let i = 0; i < candidates.length; i++) {
let label = document.createElement("label");
let who = document.createElement("input")
setAttributes(who, {
"type": "radio",
"id": candidates[i].name,
"name": candidates[i].name,
"value": candidates[i].name
})
label.setAttribute("for", candidates[i].name);
label.innerHTML = candidates[i].name;
mainContainer.appendChild(label);
mainContainer.appendChild(who);
console.log("in")
}
}
addCandidatesToHtml();
这里是HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/main.js"></script>
<title>Vote</title>
</head>
<body>
<form id="candidatesGoHere" action="" class="form-control">
</form>
</body>
</html>
问题是循环似乎没有运行!我不知道为什么会这样,我花了很多时间研究和尝试不同类型的循环,但一无所获。
提前感谢!
按如下方式修改代码
const getCandidates = async () => {
let candidates = [];
return axios
.get(
"<a certain endpoint here, the endpoint is good, that is not the problem>"
)
.then((response) => {
console.log(response);
for (let i = 0; i < response.data.candidates.length; i++) {
candidates.push(response.data.candidates[i]);
}
console.log(candidates);
return candidates;
});
};
function setAttributes(el, attrs) {
for (let key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
async function addCandidatesToHtml() {
const candidates = await getCandidates();
let mainContainer = document.getElementById("candidatesGoHere");
for (let i = 0; i < candidates.length; i++) {
let label = document.createElement("label");
let who = document.createElement("input");
setAttributes(who, {
type: "radio",
id: candidates[i].name,
name: candidates[i].name,
value: candidates[i].name,
});
label.setAttribute("for", candidates[i].name);
label.innerHTML = candidates[i].name;
mainContainer.appendChild(label);
mainContainer.appendChild(who);
console.log("in");
}
}
addCandidatesToHtml();
- 从getCandidates函数返回promise,也使该函数为异步
- 从addCandidatedToHTMl调用getCandidates函数,并使用await等待直到promise被解决,一旦promise被解决,您可以将promise的返回值存储在候选者中,并可以在函数 中使用它