jQuery on() method only works indirectly via childSelector

吃可爱长大的小学妹 提交于 2019-12-11 13:03:27

问题


Any ideas what could be the reason that the code

$('body').on('click', '.btn_add', function(e) {alert("test");});

works, but

$('.btn_add').on('click', function(e) {alert("test");});

does not?

Thanks,


回答1:


It is event delegation:

Syntax is :

$(staticparent).on(event, selector, fn);

in this syntax selector is not a part of DOM, what it means when your page loaded this element was not there in the dom but after some js code execution this .btn_add element added in the DOM. so any event bound on page load won't be registered for this element.

so in your case if .btn_add is created dynamically then you have to delegate the event to the closest static parent, body or to document itself.

Here is a test case for event not bound on dynamic content.

$('button').on('click', function() {
  $('<button/>', {
    text: "Dynamic button"
  }).appendTo('body');
  alert(this.textContent);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Static</button>

Here is a test case for event bound on dynamic content.

$('body').on('click', 'button', function() {
  $('<button/>', {
    text: "Dynamic button"
  }).appendTo('body');
  alert(this.textContent);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Static</button>


来源:https://stackoverflow.com/questions/29073931/jquery-on-method-only-works-indirectly-via-childselector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!