我在运行时使用for循环生成了一个复选框,现在我想为每个复选框附加检查事件...如何在jquery中实现相同的。
我正在使用table .. td ..来添加checkBox。
<script>
var genTable = "<table border='1' style='border-collapse:collapse' cellpadding='5' width='100%'><thead><tr><td><input type='checkBox' id='mainCheck' /></td><td>ID</td><td>ArticleTitle</td><td>ArticleDate</td></tr></thead>";
for (i = 0; i < result.length; i++) {
if (result[i].IsImageAvailable == "TRUE") {
iChecked = "";
}
else {
iChecked = "disabled = disabled";
}
genTable += "<tr><td width='2%'>
<!--Here is my checkBox on which i want to attach checked event-->
<input type='checkBox' id='chkBox" + i + "' onchange='FillSecondGrid(" + result[i].ArticleID + ")' />
</td><td width='5%'>" + result[i].ArticleID + "</td><td>" + result[i].ArticleTitle + "</td><td width='5%'>" + result[i].ArticleDate + "</td></tr>";
}
genTable += "</tbody></table>";
document.getElementById("gridFirst").innerHTML = genTable;
</script>
答案 0 :(得分:3)
当您在script
代码中生成复选框标记时,您只需在复选框生成后添加onchange
事件:
<script>
// .. checkbox generation here ..
$('table').find('input[type=checkbox]').change(function () { /* do things on change here */ });
</script>
或者,只需在文档准备就绪的所有复选框元素上使用.on
:
$(function () {
// on document ready..
$('table input[type=checkbox]').on('change', function() { /* do things on change here */ });
}
.on
方法将捕获文档就绪后创建的任何新复选框(以及已存在的复选框)并附加您的onchange
事件。
答案 1 :(得分:1)
此处没有答案通过该事件,您需要查看是否选中了复选框。这是一个跨浏览器代码段,它将事件附加到作为给定元素的子元素的所有复选框,并在单击该复选框时打开或关闭。
var checkboxes = $(element).find("input[type=\"checkbox\"]");
$(checkboxes).change(function (event) {
// These two lines compensate for getting the event and checkbox when in ie.
if (!event) { var event = window.event; }
var checkbox = event.target || event.srcElement;
if (checkbox.checked)
alert("Checkbox is checked");
else
alert("Checkbox is not checked");
});
我认为jQuery事件实际上并不需要两个补偿行,但是放在那里非常有用,这样你的代码也可以不用于任何jQuery事件。
答案 2 :(得分:0)
你可以使用live()。这是一个例子(请检查语法等):
$('.someclassforyourcheckbox').live('change', function(){//do your stuff})
答案 3 :(得分:0)
在您的复选框中添加一个课程
<input class="dynChk" type='checkBox' id='chkBox" + i + "' onchange='FillSecondGrid(" + result[i].ArticleID + ")' />
然后使用delegate
或live
$("table").delegate(".dynChk",'change',function(){
//your code
});
live
$(".dynChk").live("change",function(){
//your code
});