gpt4 book ai didi

javascript - HTML 复选框生成选中或单击事件绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 08:56:04 25 4
gpt4 key购买 nike

我已经通过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 事件不起作用。您有什么想法让它发挥作用吗?

最佳答案

在创建完它们之后尝试绑定(bind)它们:

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"));
});
}

http://jsfiddle.net/LGcVU/

编辑:它在 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);
}

http://jsfiddle.net/hescano/LGcVU/4/

关于javascript - HTML 复选框生成选中或单击事件绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18475624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com