简体   繁体   English

如何使用Jquery选择动态添加的元素

[英]How to select dynamically added elements with Jquery

I'm loading some html using jQuery function .load() and everything works fine. 我正在使用jQuery函数.load()加载一些html,并且一切正常。 The problem is that I need to select some of the dynamic created elements to apply some styles with JS. 问题是我需要选择一些动态创建的元素以使用JS应用某些样式。 For example: 例如:

$(".new-element-class").datepicker();

I know that dynamically added elements are not part of DOM and that I can trigger events this way: 我知道动态添加的元素不是DOM的一部分,并且我可以通过以下方式触发事件:

$("body").on("click", ".new-element-class", function() {});

I have read a lot of answers with that solution but that's not what I need. 对于该解决方案,我已经读了很多答案,但这不是我所需要的。 I want to select and apply a function without having to wait for an event. 我想选择并应用函数而不必等待事件。 I also tried find() and it didn't work. 我也尝试过find() ,但是没有用。

You need to call .datepicker() in the code that adds the new element dynamically. 您需要在动态添加新元素的代码中调用.datepicker() You can do this in the callback function of .load() 您可以在.load()的回调函数中执行此操作

$("#element").load("url", function() {
    $(this).find(".new-element-class").datepicker();
});

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

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