我已经通过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事件不起作用。你对如何使其有效有任何想法吗?
答案 0 :(得分:0)
替换
newOption.onclick = function(event) {
alert('alert');
};
使用:
newOption.addEventListener('click', function() {
alert('alert');
});
答案 1 :(得分:0)
在创建全部之后尝试绑定它们:
anwsersCount = 5;
questionBodyContainer = document.getElementById('questionBody');
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");
newOptionLabel.innerHTML = "Dummie Text";
questionBodyContainer.appendChild(newOption);
questionBodyContainer.appendChild(newOptionLabel);
questionBodyContainer.innerHTML += "<p>";
}
checks = questionBodyContainer.getElementsByTagName("input");
for (var i = 0; i < checks.length; i++)
{
checks[i].addEventListener('click', function() {
alert(this.getAttribute("id"));
});
}
编辑:它在for循环中不起作用的原因是因为您在更新DOM后使用innerHTML
属性。如果您必须添加新段落,请不要通过该属性添加它,以添加其他元素的相同方式添加它:
anwsersCount = 5;
questionBodyContainer = document.getElementById('questionBody');
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");
newOptionLabel.innerHTML = "Dummie Text";
questionBodyContainer.appendChild(newOption);
questionBodyContainer.appendChild(newOptionLabel);
questionBodyContainer.appendChild(document.createElement("p"));
newOption.addEventListener('click', (function()
{
alert(this.getAttribute("id"));
}), false);
}