javascript - 使用日期选择器按钮重新创建日期选择器?
问题描述
我正在尝试重构代码源。我遇到了重新创建 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,除此之外不能使用任何东西,奇怪的约束。
解决方案
原因是; 第一次呈现页面时,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();
});
推荐阅读
- android - Gradle 构建失败并出现内存不足:Java 堆空间错误
- windows-10 - Nuget 包管理器未在 Visual Studio 2019 中恢复包
- android - 如何防止 onCreate 在 doAsync 完成之前返回结果
- db2 - DB2 中的多行到单行
- clojure - 我的开始@Clojure - 自己的代码不起作用,不要
- android - [row,col]:[20,9] 处的 ParseError 消息:预期的开始或结束标记
- ruby-on-rails - 如何为我的 Rails 应用程序扩展 sidekiq 性能。需要每秒运行 100 个 sidekiq 作业
- python - Docker start 不在控制台上提供打印输出
- wpf - 如何使用 UI 扩展现有控件
- react-native - React-native 导航:this.props.navigation.navigate 返回 undefined is not an object