$('#check_all').on('click' , function(){alert(1);});$("#yujinlist").append(html);count++; } 以上代碼執(zhí)行時,點擊#check_all時,alert一直沒反應,后在網(wǎng)上查資料時,才知道on前面的元素也必須在頁面加載的時候就存在于dom里面, 那原話是這樣的:
支持給動態(tài)元素和屬性綁定事件的是live和on,其中l(wèi)ive在JQUERY 1.7之后就不推薦使用了。現(xiàn)在主要用on,使用on的時候也要注意,on前面的元素也必須在頁面加載的時候就存在于dom里面。動態(tài)的元素或者樣式等,可以放在on的第二個參數(shù)里面。
因為我先輸出相關html,再執(zhí)行就沒問題了。
<div class="row">/<div class="col-xs-12">/<div class="control-group">/<label class="control-label bolder blue">選擇鎮(zhèn)街</label>/<div class="row">/<div class="checkbox col-xs-1">/<label>/<input type="checkbox" class="checkbox" id="check_all" />/<span class="lbl">全區(qū)</span>/</label>/</div>/<div id="check_item">/<div class="checkbox col-xs-1 ">/<label>/<input name="towm'+count+'" type="checkbox" class="checkbox" />/<span class="lbl">西南街道</span>/</label>/</div>/<div class="checkbox col-xs-1 ">/<label>/<input name="towm'+count+'" type="checkbox" class="checkbox" />/<span class="lbl">云東海街道</span>/</label>/</div>/<div class="checkbox col-xs-1">/<label>/<input name="towm'+count+'" type="checkbox" class="checkbox" />/<span class="lbl">白坭鎮(zhèn)</span>/</label>/</div>/<div class="checkbox col-xs-1">/<label class="block">/<input name="towm'+count+'" type="checkbox" class="checkbox" />/<span class="lbl">樂平鎮(zhèn)</span>/</label>/</div>/<div class="checkbox col-xs-1">/<label class="block">/<input name="towm'+count+'" type="checkbox" class="checkbox" />/<span class="lbl">大塘鎮(zhèn)</span>/</label>/</div>/<div class="checkbox col-xs-1">/<label class="block">/<input name="towm'+count+'" type="checkbox" class="checkbox" />/<span class="lbl">蘆苞鎮(zhèn)</span>/</label>/</div>/<div class="checkbox col-xs-1">/<label class="block">/<input name="towm'+count+'" type="checkbox" class="checkbox" />/<span class="lbl">南山鎮(zhèn)</span>/</label>/</div>/</div>/</div>/</div>/</div>/</div>/<hr />'; $('#check_all').on('click' , function(){var that = this;$('#check_item').find('input:checkbox').each(function(){alert(2);this.checked = that.checked;$(this).closest('.col-xs-1').toggleClass('selected');});});下面看下jquery on() 方法綁定動態(tài)元素
jQuery on()方法是官方推薦的綁定事件的一個方法。使用 on() 方法可以給將來動態(tài)創(chuàng)建的動態(tài)元素綁定指定的事件,例如append等。
<div id="test"><div class="evt">evt1</div></div>
錯誤的用法,下面方法只為第一個class 為 evt 的div 綁定了click事件,使用append動態(tài)創(chuàng)建的div則沒有綁定
<script>// 先綁定事件再添加div$('#test .evt').on('click', function() {alert($(this).text())});$('#test').append('<div class="evt">evt2</div>');</script>正確的用法如下:
<script>$('body').on('click', '#test .evt', function() {alert($(this).text())});$('#test').append('<div class="evt">evt2</div>');</script>以上所述是小編給大家介紹的jQuery on()方法綁定動態(tài)元素的點擊事件無響應的解決辦法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點
疑難解答