简体   繁体   中英

Jquery .live works but not with .datepicker

Thanks for looking, all sincerely helpful answers are up-voted. I have some date input fields that are there when the page loads and a bunch that get generated dynamically. Instead of calling .datepicker() on that class each time a new instance is generated, I'm using .live, but it doesn't seem to be working. Any idea why?

$("input[name=myfav]").live("click", function(){
    $(this).datepicker({ 
        /* some options here */ 
    });
});

I should mention, it works perfectly fine with autocomplete for instance.

$("input[name=mytwo]").live("click", function(){
    $(this).autocomplete("somefile.php");
});

Here is an article about the datepicker using the .live-event in jQuery:

http://www.vancelucas.com/blog/jquery-ui-datepicker-with-ajax-and-livequery/

The problem is that the Datepicker works by binding to the focus() event by default, but as of jQuery 1.3.2, the 'focus' event cannot be monitored by the 'live' event function.

Here is the work-around from the site::

<script type="text/javascript">
$(function(){
    $('input.calendarSelectDate').live('click', function() {
        $(this).datepicker({showOn:'focus'}).focus();
    });
});
</script>

EDIT: This workaround is no longer needed as jQuery 1.4.1+ now supports focus and blur events for live(). (Thanks @Chris S )

This is what I ended up using. It takes advantage of live and focus in newer jQuery

$.datepicker.setDefaults({ dateFormat: 'yy-mm-dd', ... });
$('input.date').live('focus', function() {
    $(this).datepicker().datepicker('show');
    true;
});

值得注意的是,jQuery 1.4.1+现在支持live()的焦点和模糊事件,因此不再需要变通方法,尽管它很酷,但是原始海报的版本很好用!

Update : As of jQuery 1.7, the .live() method is deprecated. 1.7, Use .on() to attach event handlers. Reference : http://api.jquery.com/live/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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