2011-08-19 162 views
1

我有一個在運行時使用for循環生成的checkBox,現在我想附加每個複選框的checked事件...如何在jQuery中實現相同的事件。使用JQuery動態地在checkBox上附加checked事件

我使用表.. 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

您的意思是複選框在初始頁面加載(AJAX)後添加到頁面中? – Alex

+0

我用代碼更新了我的問題......希望它能幫助你們解決我的問題,而且這是在document.ready jquery事件上調用的。 – Abbas

+0

在較新版本的JQuery(> 1.7)中,使用.on()代替(http://api.jquery.com/on/)。 – BasTaller

回答

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我thod將捕獲文檔就緒後創建的任何新複選框(以及已存在的複選框)並附加您的onchange事件。

+0

爲未來的觀衆.live是刪除,因爲jquery 1.9只是改變爲.on,而且會做。 – CaffeineShots

+0

確實,更新! – Alex

0

您可以使用live()。下面是一個例子(請檢查語法等):

$('.someclassforyourcheckbox').live('change', function(){//do your stuff}) 
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 
}); 
1

沒有回答,這裏已經過去,則您需要找出複選框是否爲c是不是聽說過。這是一個跨瀏覽器代碼片斷,它將事件附加到作爲給定元素的子元素的所有複選框,並在複選框處於打開或關閉狀態時單擊該複選框。

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的事件正常工作。

相關問題