[英]Adding an HTML element (a button to a form) when an event happens (when another button, from another form, is clicked), using EJS?
我正在構建一個Node.js服務器並使用Express。 在EJS視圖中,我有一個帶有事件偵聽器的表單,即單擊給定的單選按鈕時,將調用一個函數:
// the way thearray is created is omitted
<% for(var i=0; i<therray.length; i++) { %>
// parts omitted
<td>
<form id= <%= "question_examen"+i %> > // the form that triggers the event
<input type="radio" id= <%= "examen_non"+i %> name="examen" value="non" checked>Non
<input type="radio" id= <%= "examen_oui"+i %> name="examen" value="<%= i %>" onClick= <%= "exam("+i+")" %>>Oui
</form>
</td>
<td>
<form id= <%= "question_selection"+i %> > // the second form, empty at the beginning, but that I want to enrich (see below)
</form>
</td>
// parts omitted
<% } %>
我希望第一種形式觸發的函數check(i)將新的單選按鈕添加到第二種形式。 這是我的功能:
<script type='application/javascript'>
function exam(i) {
alert(i); // just to check it is correctly triggered (it is the case)
// code with mistakes, I guess, since it's not working:
document.createElement("inputnon");
input.type ="radio";
input.id= <%= "selection_non"+i %>;
input.name="selection";
input.value="non";
input.innerHTML="Non";
document.getElementById("#question_selection"+i).appendChild(inputnon);
document.createElement("inputoui");
input.type ="radio";
input.id= <%= "selection_oui"+i %>;
input.name="selection";
input.value="oui";
input.innerHTML="Oui";
document.getElementById("#question_selection"+i).appendChild(inputoui);
}
</script>
確實有很多錯誤:)
1)您正在嘗試使用錯誤的ID訪問第二個表單
<form id= <%= "selection_examen"+i %> >...
...
document.getElementById("#question_selection"+i).appendChild(inputoui);
2)您需要使用直接js來連接輸入的ID,不需要EJS。
要解決此問題,請執行以下操作:
input.id= "selection_non"+i;
代替:
input.id= <%= "selection_non"+i %>;
3)您在創建元素時未聲明並將其分配給變量,並且您正在創建的元素不是有效的輸入
要解決此問題,請執行以下操作:
var inputnon = document.createElement("input");
inputnon.type ="radio";
...
代替這個:
document.createElement("inputnon");
input.type ="radio";
...
input.innerHTML="Non"; ... input.innerHTML="Oui";
嘗試以下代碼(雖然未運行,所以可能會有更多錯誤):
<script>
function exam(i) {
alert(i); // just to check it is correctly triggered (it is the case)
// hopefully the following code will run:
var inputnon = document.createElement("input");
inputnon.type ="radio";
inputnon.id= "selection_non"+i;
inputnon.name="selection";
inputnon.value="non";
document.getElementById("question_selection"+i).appendChild(inputnon);
var inputoui = document.createElement("input");
inputoui.type ="radio";
inputoui.id= "selection_oui"+i;
inputoui.name="selection";
inputoui.value="oui";
document.getElementById("question_selection"+i).appendChild(inputoui);
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.