简体   繁体   English

如何绑定新添加的元素而不会发生单击,焦点等事件?

[英]How do you bind newly added element without event like click, focus, etc?

For example if I want to bind datepicker to a newly added element. 例如,如果我想将datepicker绑定到新添加的元素。 I could simply do this 我可以简单地做到这一点

$('body').on('focus', '.datepicker', function(){
    $(this).datepicker();
});​

but what if I don't want to use focus, I simply want to bind every element with .datepicker class on load. 但是,如果我不想使用焦点,我只想在加载时将每个元素与.datepicker类绑定。 Is this possible? 这可能吗?

After adding the elements dynamically, run code converting any that don't already have datepickers into ones that do. 动态添加元素之后,运行代码以将没有日期选择器的所有元素转换为具有日期选择器的元素。 jQuery's datepicker adds a .hasDatepicker class when it initializes, so: jQuery的.hasDatepicker初始化时会添加.hasDatepicker类,因此:

// After adding elements
$(".datepicker:not(.hasDatepicker)").datepicker();

If you really want to autmate it (perhaps you're not in control of the code that's adding the elements), you can use a MutationObserver on modern browsers (and polling on non-modern browsers; repeating the above every 50ms isn't going to add any significant overhead to your page). 如果您真的想对其进行自动化处理(也许您无法控制添加元素的代码),则可以在现代浏览器上使用MutationObserver (并在非现代浏览器上进行轮询;每50毫秒重复一次以上操作)在页面上增加任何重大开销)。

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

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