这是我目前掌握的情况
main.html(顺便说一句,这是一个表单)
<div class="form-group form-check-inline">
<input class="form-check-input" type="radio" name="region" id="US" value="US">
<label class="form-check-label" for="US">US</label>
</div>
api.js
document.addEventListener('DOMContentLoaded', () => {
const urlUS = new URL("http://127.0.0.1:3000/api/v1/regionApi/regionProduct/1")
document.getElementById('US').addEventListener('click', getRegionUS)
function getRegionUS() {
fetch(urlUS, {
method:'GET'
})
.then(res => res.json())
.then(data => {
data.forEach(function(product){
output = `
<div class="form-group form-check">
<input class="form-check-input" type="checkbox" value="${product.productname}" id="${product.id}">
<label class="form-check-label" for="${product.id}">
${product.productname}
</label>
</div>
`
})
document.getElementById('US').innerHTML = output
console.log(data)
})
.catch(error => console.log('error'))
}
})
当我点击单选按钮时,我确实得到了我在API中寻找的信息。我错过了什么?为什么它没有出现在复选框中?我应该尝试什么?
2条答案
按热度按时间zfciruhq1#
你的代码似乎有一些问题...
1.您正在替换
foreach
外部的HTML,但它只使用对output
的最后一次赋值,因为每次迭代都会覆盖它。1.您正试图将HTML***添加到***复选框输入元素中,这是不允许的。
你需要构建HTML,每次迭代都添加到HTML中,然后再将其全部插入到页面中。你还需要在页面上的其他地方添加生成的HTML。见下文
yrwegjxp2#
这可以更优雅和简洁-我在这里从容器进行委托
注意我重用了另一个答案中的JSON模拟数据url。更改product.whatever以匹配您的对象