Making datepicker live - JQuery

后端 未结 4 719
故里飘歌
故里飘歌 2021-01-12 09:48

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

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

相关标签:
4条回答
  • 2021-01-12 10:07

    I think that more proper solution is:

    $('input.datepickerClass').live('focus', function(){
        if (false == $(this).hasClass('hasDatepicker')) {
            $(this).datepicker({ options });
        }
    });
    
    0 讨论(0)
  • 2021-01-12 10:13

    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.

    0 讨论(0)
  • 2021-01-12 10:13

    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.

    0 讨论(0)
  • 2021-01-12 10:16

    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.

    0 讨论(0)
提交回复
热议问题