1 回答

TA貢獻1872條經驗 獲得超4個贊
您不能有重復的 ID。
您使用 form.name 而不是腳本中的 ID。更改為類并遍歷 document.querySelectorAll(".formClass")
為什么不對城市和首都進行 JSON 編碼,而只是在腳本中使用它們呢?然后您可以在客戶端生成表單
我的建議 - 未經針對您的陣列進行測試,因為我沒有您的城市和資本陣列的示例。
const states = {
"Odisha": ["Bhubaneswar"],
"Andhra Pradesh": ["Amaravati", "Hyderabad"]
} // <?php echo json_encode(states); ?>;
const form = document.getElementById("main");
let html = ['<fieldset>']
Object.keys(states).forEach(state => html.push(`<label>What is the capital of ${state}?</label> <input type="text" data-state="${state}" placeholder="Enter answer" name="city[]" required />`));
html.push('<button type="button" id="checkBut">Check</button> <div readonly id="total"></div>')
html.push('</fieldset>')
form.innerHTML = html.join('<hr>')
window.addEventListener("load", function() {
document.getElementById("checkBut").addEventListener("click", () => {
let c = 0;
[...document.querySelectorAll("[name^=city]")].forEach(input => c += states[input.getAttribute("data-state")].indexOf(input.value) !== -1 ? 1 : 0);
document.getElementById("total").innerText = "Your Score is " + c;
});
});
#score {
width: 80%
}
fieldset {
min-width: 500px;
display: inline-block;
}
fieldset input {
float: right;
}
#total {
float: right;
}
<div id="score">
<form id="main">
</form>
</div>
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報