开发者

Binding jQuery UI plugin after $.load

开发者 https://www.devze.com 2022-12-29 01:32 出处:网络
I have a function that attaches the jQuery UI DatePicker (with my options) to a passed jQuery object:

I have a function that attaches the jQuery UI DatePicker (with my options) to a passed jQuery object:

function bindDatepicker($obj)
{
  if ($obj == null) $obj = $("input.date");

  $obj.datepicker(
    { 
      appendText: '(yyyy-mm-dd)',
      autoSize: true,
      changeMonth: true, 
      changeYear: true, 
      closeText: 'Done',
      dateFormat: 'yy-mm-dd',
      defaultDate: '+1m', 
      minDate: +1, 
      numberOfMonths: 2
    }
  );
}

I call this at the beginning of every page to bind it to input elements:

$(function() {
  bindDatepicker($("input.date"));
});

This works fine. My problem comes in when I load form elements using $.load(). I cannot attach the DatePicker to any of the loaded elements. For example:

$("#id").load("urlToLoad", function() {
    bindDatepicker($("input.date"));
});

Loads the form elements into a div just fine开发者_如何转开发, but will not attach the DatePicker.

Why is this? I am stumped. :(

Thanks, Tom


You need to use the jQuery .live() method. It will "listen" for any new elements that match your selector criteria.

EDIT: So my original answer was wrong. The .live() method is only for binding events. As you have pointed out in your comments you can't actually bind to an event if there's no event to bind to. So I decided to whip up a sample and see if I could reproduce your problem and I could. What was weirder tho, was if I tried to use an attribute based selector, rather than a class selector, it worked perfectly.

So instead of doing

$('input.date').datepicker();

I stuck a new attribute on there called 'type' and had the following selector:

$('[type=date]').datepicker();

and everything worked.

I have no idea why this is but I can only assume it's a bug with jQuery.

0

精彩评论

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