【问题标题】:Recreating a DatePicker using datepicker button?使用日期选择器按钮重新创建日期选择器?
【发布时间】:2021-08-18 05:54:00
【问题描述】:

我正在尝试重构代码源。 我遇到了重新创建 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,除此之外不能使用任何东西,奇怪的约束。

【问题讨论】:

  • 因为您正在单击一个没有单击处理程序的新元素。查看event delegation
  • 你能告诉我使用 Fiddle 吗?使用我的日期选择器选项?无法触发 #datepicker 静态祖先的事件 - 假设是
  • 嗯,你是对的,看起来事件的传播正在停止。鉴于您的用例看起来像 beforeShow 会起作用。以后有时间我再看看。

标签: javascript jquery datepicker


【解决方案1】:

原因是;第一次呈现页面时,为.myclass 元素注册了click 事件。但是,当这些元素被销毁时,附加的事件侦听器也会被销毁。即使它们再次出现在页面中,新事件也不会自动附加,因为该事件附加代码不会再次运行。 有两种选择;
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();
});

【讨论】:

  • 在这个 mah 工作的同时,我已经更新了原始问题,但有点复杂。
  • 我为 jQuery 1.3 添加了解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
  • 2019-06-30
  • 2014-04-22
  • 2021-07-28
相关资源
最近更新 更多