:HTML複選框選中生成或點擊我已經被JS所產生的複選框事件綁定
anwsersCount = question.ChoiceQuestionAnwsers().length;
questionBodyContainer = document.getElementById('questionBody');
//self.ChoosedQuestionAnwsers = question.ChoiceQuestionAnwsers;
for (var i = 0; i < anwsersCount; i++) {
var newOption = document.createElement("input");
var newOptionLabel = document.createElement("label");
newOption.type = "checkbox";
newOption.id = i;
newOption.value = i;
newOptionLabel.for = i;
newOptionLabel.setAttribute("style", "margin-left: 5px");
newOption.onclick = function(event) {
alert('alert');
};
newOptionLabel.innerHTML = question.ChoiceQuestionAnwsers()[i].Text;
// questionBodyContainer.innerHTML += question.ChoiceQuestionAnwsers()[i].Text + "<p>";
// questionBodyContainer.appendChild(newOption);
questionBodyContainer.appendChild(newOption);
questionBodyContainer.appendChild(newOptionLabel);
questionBodyContainer.innerHTML += "<p>";
//self.ChoosedQuestionAnwsers.push(question.ChoiceQuestionAnwsers()[i]);
}
和onclick事件的生成複選框不到風度的工作。你有什麼想法如何使它工作?
完善!謝謝:)你能解釋一下爲什麼在新循環內工作嗎?我在學習JS :) – duch1989
循環內部不起作用的原因是因爲在DOM中添加元素之後,通過添加帶有innerHTML屬性的新段落來修改DOM。刪除它,你應該能夠在for循環中添加事件監聽器。 http://jsfiddle.net/hescano/LGcVU/2/ –
你可以看看我的編輯。 –