开发者

Making datepicker live - JQuery

开发者 https://www.devze.com 2023-03-17 14:46 出处:网络
I know when you create an element dynamically, you have to use something like: $(\"#id\").live(\"click\", function() {

I know when you create an element dynamically, you have to use something like:

$("#id").live("click", function() {
    //something
});

Right now I have this:

$('#tdInput1').datepicker({
    inline: true
});

My question is: how do 开发者_运维技巧I make this live so it can interact with dynamically created elements.


The accepted solution won't work with keyboard focus events.. so I had to change to this:

$('.parent').on('focusin', '.datepicker', function(e) {
    $(this).datepicker(options);
});

Had to change .live to .on since jquery 1.9.1 doesn't include the .live method. The above works for the mouse events as well as keyboard focus events.


According to: Jquery .live works but not with .datepicker

This should work:

$("#tdInput1").live("click", function(){
    $(this).datepicker({ 
        inline: true 
    });
});

edit: This answer is for older versions of jQuery. For jQuery 1.9+ please try Vishal's answer.


You're dealing with two different things. jQuery's live is for event binding, while datepicker is not specifically tied to an event, but rather just adds functionality to an element at a moment in time.

The only reason live works with events is that jQuery actually attaches the event handler to an ancestor element, and (thanks to the way events bubble up in javascript), the ancestor actually receives the event and delegates it as if it came from the element. The principle is kind of complicated, but long and short, it could only work with events.

If you want to add datepicker functionality, simply call the datepicker function on the new element after it's created.


I think that more proper solution is:

$('input.datepickerClass').live('focus', function(){
    if (false == $(this).hasClass('hasDatepicker')) {
        $(this).datepicker({ options });
    }
});
0

精彩评论

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