开发者

JQuery: delegate and datepicker

I need that every text input in a given class is a datepicker. Something like:

$("input[type=text].time").datepicker();

but I'm adding a lot of code via Jquery.load() so I believe I need a开发者_StackOverflow中文版 delegate. The problem is I don't know how to do it, because as far as I know, load event cannot be used in a delegate. It will be easy if it exists:

$(document).delegate("input[type=text].time", "load", function(){
    $(this).datepicker();
});


$("body").delegate("input[type=text].time", "focusin", function(){
   $(this).datepicker();
});

I used delegate on the body because I don't know if you have your code in other containers that you can target.

Here is a fiddle that targets a specific div with delegate:

http://jsfiddle.net/MpqAy/


I know this question is relatively old but I just wanted to share my solution as it's still relevant in 2018.

 $('#container').off().on('focusin', '.date', function () => {
     $(this).datepicker();
 });

If you're using jQuery with TypeScript

 $('#container').off().on('focusin', '.date', (e) => {
     $(e.currentTarget).datepicker();
 });

You'll notice the off() function here. This will wipe out events from the Jquery object in question. So you won't get any bubbling issues. Keep in mind though, that it kills all events on that object and not just the event you're running again.

I wouldn't recommend using off() or on() on document, html, or body level jQuery objects. Just my opinion though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜