2014-07-23 24 views
0

添加的元素使用日期选择器下面是到目前为止我的代码:

$('body').on('change', '.dropdown', function() { 
    $.ajax({ 
     success: function(res) { 
      if(res.success == true) { 
       return elements with class .hasdatepicker 

       getdatepicker('.hasdatepicker'); 
      } 
     } 
    }); 
}); 

function getdatepicker(elem) { 
    $(elem).each(function(){ 
     var currentYear = (new Date).getFullYear(); 
     var objdate = $(this); 
     $(this).datepicker({ 
      changeMonth: true, 
      changeYear: true, 
      yearRange: '1950:currentYear', 
      onChangeMonthYear: function(year, month, inst) { 
       objdate.val(month+'/'+inst.selectedDay+'/'+year); 
      } 
     }); 
     $(this).attr("readonly","true"); 
    }); 
} 

我知道它得到getdatepicker,因为它增加了readonly属性的元素。

谢谢你的帮助!

编辑:我真的很抱歉的混乱。我更新了我的答案。我的功能getdatepicker实际上是在拨打success之内..

+3

Ajax中的** A **。 –

+0

@DaveNewton正确 - 异步JavaScript和XML。 –

回答

1

您应该将getDatePicker()放入ajax调用的成功函数中。 你现在正在呼吁它的方式是运行成功方法之前: 例子:

HTML:

<div id='test'>test</div> 

JS:

$(document).on('click', '#test', function() { 
$.ajax({ 
    success: function() { 
     $("#test").addClass('hasdatepicker') 
     getdatepicker($('.hasdatepicker')); //SUCCESS 
    } 
}); 

getdatepicker($('.hasdatepicker')); //FAIL 
}); 

function getdatepicker(elem) { 
    elem.html('success'); 
} 
1

你需要调用你的函数在Ajax回调,这是因为当getdatepicker运行时ajax.success尚未运行,因为ajax.success是异步的。

$('body').on('change', '.dropdown', function() { 
    $.ajax({ 
     success: function() { 
     //return elements with class .hasdatepicker ; 
     getdatepicker('.hasdatepicker');} 
    }); 
});