1

我有一个在运行时使用for循环生成的复选框,现在我想为每个复选框附加选中的事件......如何在jquery中实现相同的。

我正在使用表格.. td.. 来添加复选框。

<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>
4

4 回答 4

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事件。

于 2011-08-19T18:17:09.077 回答
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 事件实际上需要这两条 ie 补偿线,但放在那里很有用,这样您的代码也可以在没有 jQuery 事件的情况下工作。

于 2012-07-20T09:22:28.557 回答
0

您可以使用 live() 。这是一个示例(请检查语法等):

$('.someclassforyourcheckbox').live('change', function(){//do your stuff})
于 2011-08-19T18:03:41.443 回答
0

在您的复选框中添加一个类

<input class="dynChk" type='checkBox' id='chkBox" + i + "' onchange='FillSecondGrid(" + result[i].ArticleID + ")' />

然后使用delegatelive

$("table").delegate(".dynChk",'change',function(){
//your code
});

live

$(".dynChk").live("change",function(){
//your code
});
于 2011-08-19T18:23:44.237 回答