[英]$(document).on(..) event works but not $(“body”).on(..) for dynamically generated element
我已經動態創建了元素
<a class="update-link">
path: body > div#MySection > table> tbody > tr > td > div > a.update-link
。
當我使用綁定事件
$(document).on("click", ".update-link", fn)
事件被觸發。
當我使用$("body")
或$("#MySection")
,不會觸發該事件。 $(document)
可以工作,但是由於范圍大而效率低下。 為什么更具體的選擇器不起作用?
您可以通過事件委托傳遞上下文:
$(() => { $(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>
因此,在您的情況下, .sec
將是body
或#MySection
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.