jQuery on()方法綁定動態元素的點擊事件無響應的解決辦法,jqueryon
$('#check_all').on('click' , function(){alert(1);});$("#yujinlist").append(html);count++; }
以上代碼執行時,點擊#check_all時,alert一直沒反應,後在網上查資料時,才知道on前面的元素也必須在頁面載入的時候就存在於dom裡面, 那原話是這樣的:
支援給動態元素和屬性綁定事件的是live和on,其中live在JQUERY 1.7之後就不推薦使用了。現在主要用on,使用on的時候也要注意,on前面的元素也必須在頁面載入的時候就存在於dom裡面。動態元素或者樣式等,可以放在on的第二個參數裡面。
因為我先輸出相關html,再執行就沒問題了。
<div class="row">\<div class="col-xs-12">\<div class="control-group">\<label class="control-label bolder blue">選擇鎮街</label>\<div class="row">\<div class="checkbox col-xs-1">\<label>\<input type="checkbox" class="checkbox" id="check_all" />\<span class="lbl">全區</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">白坭鎮</span>\</label>\</div>\<div class="checkbox col-xs-1">\<label class="block">\<input name="towm'+count+'" type="checkbox" class="checkbox" />\<span class="lbl">樂平鎮</span>\</label>\</div>\<div class="checkbox col-xs-1">\<label class="block">\<input name="towm'+count+'" type="checkbox" class="checkbox" />\<span class="lbl">大塘鎮</span>\</label>\</div>\<div class="checkbox col-xs-1">\<label class="block">\<input name="towm'+count+'" type="checkbox" class="checkbox" />\<span class="lbl">蘆苞鎮</span>\</label>\</div>\<div class="checkbox col-xs-1">\<label class="block">\<input name="towm'+count+'" type="checkbox" class="checkbox" />\<span class="lbl">南山鎮</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() 方法綁定動態元素
jQuery on()方法是官方推薦的綁定事件的一個方法。使用 on() 方法可以給將來動態建立的動態元素繫結指定的事件,例如append等。
<div id="test"><div class="evt">evt1</div></div>
錯誤的用法,下面方法只為第一個class 為 evt 的div 綁定了click事件,使用append動態建立的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()方法綁定動態元素的點擊事件無響應的解決辦法,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!