简体   繁体   English

$(document).on(..)事件有效,但动态生成的元素的$(“ body”)。on(..)事件无效

[英]$(document).on(..) event works but not $(“body”).on(..) for dynamically generated element

I have dynamically created element 我已经动态创建了元素

<a class="update-link">

with path: body > div#MySection > table> tbody > tr > td > div > a.update-link . path: body > div#MySection > table> tbody > tr > td > div > a.update-link

When I bind event using 当我使用绑定事件

$(document).on("click", ".update-link", fn) 

The event is triggered. 事件被触发。

When I use $("body") or $("#MySection") , the event is not triggered. 当我使用$("body")$("#MySection") ,不会触发该事件。 $(document) works but is inefficient due to the large scope. $(document)可以工作,但是由于范围大而效率低下。 Why don't the more specific selectors work? 为什么更具体的选择器不起作用?

You can pass a context through with your event delegation: 您可以通过事件委托传递上下文:

 $(() => { $(document, ".sec", "button").on("click", () => { console.log("clicked"); }); $(".sec").append("<button>Test</button>"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="sec"></section> 

So in your case, .sec would be body or #MySection . 因此,在您的情况下, .sec将是body#MySection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM