2010-08-03 40 views
0

我正在使用现有的JavaScript库,它执行AJAX调用,然后执行可选的回调函数。回调函数传递正在加载到DOM中的HTML字符串。我需要将jQuery datepicker分配给该HTML字符串中日历类的所有元素。jQuery提取id然后根据类别附上日历

从AJAX查询HTML字符串的一个简单的例子是:

<tr id='1234'> 
    <td> 
     <input type="text" value="somevalue" /> 
     <input type="text" class="calendar" value="21/12/2010" /> 
    </td> 
    <td> 
     <input type="text" value="someothervalue" /> 
     <input type="text" class="calendar" value="21/12/2011" /> 
    </td> 
</tr> 

我可以执行在回调函数下面以设置两个所需投入的日期选择器,但是,是造成奇怪的事情发生随着日期选择器,例如从2010年的下一个按钮跳转到1900年以前的按钮跳转到1899年

$(".calendar").datepicker('destroy').datepicker({ dateFormat: 'dd/mm/yy', showAnim: 'fadeIn', duration: 200, gotoCurrent: true, changeYear: true, yearRange: 'c-120:c' }); 

因此我想,而不是仅仅局限于HTML代码段内声明的元素提供给回调f结。我可以使用哪些jQuery的模式acheive以下结果指出,HTML参数是一个字符串:

function SetCalendar(html) { 
    $("html.children .calendar").datepicker('destroy').datepicker({ dateFormat: 'dd/mm/yy', showAnim: 'fadeIn', duration: 200, gotoCurrent: true, changeYear: true, yearRange: 'c-120:c' }); 

}

回答

0

可能有更好的方法,但这个工程。我仍然遇到了令人讨厌的问题,即datepicker上的下一个按钮从2010年7月跳到1900年1月,但我猜这是datepicker代码中的其他内容。

function SetCalendar(html) { 
    var id = "#" + /.*?id="(.*?)"/.exec(html)[1]; 
    $(id).find('input.calendar').datepicker('destroy').datepicker({ 
      dateFormat: 'dd/mm/yy', 
      showAnim: 'fadeIn', 
      duration: 200, 
      gotoCurrent: true, 
      changeYear: true, 
      yearRange: 'c-120:c' 
    }); 
} 
1

你几乎拥有了。如果你使用这个作为你的ajax成功函数。

function ajaxSuccessFn(html) { 
    $(html).find('input.calendar').datepicker({ 
      dateFormat: 'dd/mm/yy', 
      showAnim: 'fadeIn', 
      duration: 200, 
      gotoCurrent: true, 
      changeYear: true, 
      yearRange: 'c-120:c' 
    }).end().appendTo('#someElement'); 
} 
+0

这不会导致在输入上设置日期选择器。我用jQuery不太好,但在你的例子中,html不需要成为一个DOM元素来工作吗?在我的情况下,html只是一个字符串,代表一些已被动态加载到DOM中的html。 – sipwiz 2010-08-03 00:37:05

+0

@sipwiz,我以为你是通过这个函数从ajax调用的响应?如果你已经将它添加到dom中,那么这将不起作用。显示更多代码可能很有用,例如,将响应添加到dom的ajax调用的成功部分。我已经改变了我的答案,以展示如何去做这件事。 – redsquare 2010-08-03 00:46:00