将 datepicker() 放在动态创建的元素上 - JQuery/JQueryUI
我动态创建了文本框,我希望每个文本框都能在点击时显示日历.我使用的代码是:
I have dynamically created textboxes, and I want each of them to be able to display a calendar on click. The code I am using is:
$(".datepicker_recurring_start" ).datepicker();
它只适用于第一个文本框,即使我所有的文本框都有一个名为 datepicker_recurring_start 的类.
Which will only work on the first textbox, even though all my textboxes have a class called datepicker_recurring_start.
非常感谢您的帮助!
这里有诀窍:
$('body').on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});
$('...selector..').on('..event..', '...another-selector...', ...callback...);
语法表示:
为事件 ..event..
('focus'在我们的例子中).对于与选择器 ...another-selector...
(在我们的示例中为 .datepicker_recurring_start
)匹配的匹配节点的所有后代,应用事件处理程序 ...回调...
(我们示例中的内联函数)
The $('...selector..').on('..event..', '...another-selector...', ...callback...);
syntax means:
Add a listener to ...selector..
(the body
in our example) for the event ..event..
('focus' in our example). For all the descendants of the matching nodes that matches the selector ...another-selector...
(.datepicker_recurring_start
in our example) , apply the event handler ...callback...
(the inline function in our example)
参见 http://api.jquery.com/on/,尤其是关于的部分委托事件"
See http://api.jquery.com/on/ and especially the section about "delegated events"