首页 > 解决方案 > 使用日期选择器按钮重新创建日期选择器?

问题描述

我正在尝试重构代码源。我遇到了重新创建 Jquery DatePicker 的问题。

我的 DatePicker 已经初始化如下:

$("#datepicker").datepicker({ 
            showOn : "button", 
          buttonText: "<i id='really' class='myclass'>Show</i>",
          dateFormat: 'dd/mm/yy'});

但是,按钮类 - myclass ,我正在使用该按钮来刷新 datePicker 选项。

$(".myclass").click(function(){
       //destroy the old datepicker.
       $("#datepicker").datepicker("destroy");
   
      //do something probably async here.
      doSomething();
 
      //Recreate the same with some other options
     $("#datepicker").datepicker({
          showOn : "button", 
          //More options go here. But buttonText remains the same.
          buttonText: "<i id='really' class='myclass'>Show</i>",
          dateFormat: 'dd/mm/yy'});
});

我的日期选择器刷新,但是我无法通过单击具有相同类的“新”日期选择器按钮再次触发相同的方法。

有人能帮我吗 ?

更新:我正在使用 JQuery 1.3.2,除此之外不能使用任何东西,奇怪的约束。

标签: javascriptjquerydatepicker

解决方案


原因是; 第一次呈现页面时,click.myclass元素注册事件。但是,当这些元素被销毁时,附加的事件侦听器也会被销毁。即使它们再次出现在页面中,新事件也不会自动附加,因为该事件附加代码不会再次运行。有两种选择;
1- 使用 .myclass 选择器侦听父元素单击事件:
HTML:

<div id="picker-area">
  <div id="datepicker"></div>
</div>

JS(用于 jQuery 1.3+):

$('#picker-area .myclass').live('click', function() {
  // this fn. will be attached to #picker-area with .myclass children selector. so even if new .myclass elements are appended, this function will continue to work.

  //destroy the old datepicker, etc.
});

JS(用于 jQuery 1.7+):

$('#picker-area').on('click', '.myclass', function() {
  // this fn. will be attached to #picker-area with .myclass children selector. so even if new .myclass elements are appended, this function will continue to work.

  //destroy the old datepicker, etc.
});

2- 创建新的 .myclass 元素后重新附加单击事件侦听器:

function reCreateDatePicker() {
  //destroy the old datepicker.
  $("#datepicker").datepicker("destroy");
   
  //do something probably async here.
  doSomething();
 
  //Recreate the same with some other options
  $("#datepicker").datepicker({
    showOn : "button", 
    //More options go here. But buttonText remains the same.
    buttonText: "<i id='really' class='myclass'>Show</i>",
    dateFormat: 'dd/mm/yy'});

  $(".myclass").click(function(){
    reCreateDatePicker();
  });
}

$(".myclass").click(function(){
  reCreateDatePicker();
});

推荐阅读