![](/img/trans.png)
[英]how do I get the content of a div element relative to another div element using javascript?
[英]How do I get a HTML div element to loop using javascript?
我有一個代碼塊,一個測驗創建模板,我需要該問題的代碼塊和可能的答案循環,無論用戶要求多少次。 我已經嘗試了幾個小時,我真的不確定出了什么問題。
<div id="questionform" class="modal">
在這行代碼下,我已經有了用戶想要的問題數量。
var amount = prompt("Please enter the amount of questions you would like", "<amount goes here>");
下面是我用來嘗試在 div 中循環寫作的 javascript。
var i;
var amount;
var contents = document.getElementById("questionform").innerHTML;
for (i = 1; i=amount; i++) {
a.document.write(contents);
}
您在 for 循環中的條件是錯誤的。 你有一個作業而不是一個評估。
for (i = 1; i=amount; i++)
您應該創建元素並將它們附加到 DOM。 避免使用document.write
。 另外,請從零開始索引,除非您需要從 1 開始。
如果您為輸入字段提供 name 屬性,它們將在提交時與表單一起提交。
input.setAttribute('name', 'answer[]');
當您點擊提交時,輸入字段值將被發送到服務器:
answer=foo&answer=bar
或者:
{ "answer" : [ "foo", "bar" ] }
如果您仍然感到困惑,請參閱此: 從沒有 javascript 的 HTML 表單發布數組
let amount = prompt("Please enter the amount of questions you would like", 5); let questionForm = document.getElementById("question-form"); let answerList = questionForm.querySelector(".answer-list"); for (let i = 0; i < amount; i++) { let inputWrapper = document.createElement('DIV'); let label = document.createElement('LABEL'); let input = document.createElement('INPUT'); input.setAttribute('type', 'text'); input.setAttribute('name', 'answer[]'); label.textContent = 'Answer ' + String.fromCharCode(i + 65) + ': '; inputWrapper.classList.add('input-wrapper'); inputWrapper.appendChild(label); inputWrapper.appendChild(input); answerList.appendChild(inputWrapper); }
.input-wrapper { margin-bottom: 0.25em; } .input-wrapper label { display: inline-block; width: 5em; font-weight: bold; }
<form id="question-form" class="modal"> <div class="answer-list"></div> <button type="submit">Submit</button> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.