所以我正在使用 jQuery 日期选择器,它运行良好。我正在使用 AJAX 来获取一些内容,显然,当应用此新内容时,绑定(bind)会丢失,我 learnt about this last week并发现了 .live()
方法。
但是我如何将其应用到我的日期选择器中?因为这不是一个事件,因此 .live()
将无法提供帮助......对吧?
这是我用来将日期选择器绑定(bind)到我的输入的代码:
$(".datefield").datepicker({showAnim:'fadeIn',dateFormat:'dd/mm/yy',changeMonth:true,changeYear:true});
我不想每次 AJAX 触发时都调用此方法,因为我希望尽可能保持通用。
干杯:-)
编辑
按照 @nick 的要求,下面是我的包装函数,它获得了 ajax()
方法:
var ajax_count = 0;
function getElementContents(options) {
if(options.type===null) {
options.type="GET";
}
if(options.data===null) {
options.data={};
}
if(options.url===null) {
options.url='/';
}
if(options.cache===null) {
options.cace=false;
}
if(options.highlight===null || options.highlight===true) {
options.highlight=true;
} else {
options.highlight=false;
}
$.ajax({
type: options.type,
url: options.url,
data: options.data,
beforeSend: function() {
/* if this is the first ajax call, block the screen */
if(++ajax_count==1) {
$.blockUI({message:'Loading data, please wait'});
}
},
success: function(responseText) {
/* we want to perform different methods of assignment depending on the element type */
if($(options.target).is("input")) {
$(options.target).val(responseText);
} else {
$(options.target).html(responseText);
}
/* fire change, fire highlight effect... only id highlight==true */
if(options.highlight===true) {
$(options.target).trigger("change").effect("highlight",{},2000);
}
},
complete: function () {
/* if all ajax requests have completed, unblock screen */
if(--ajax_count===0) {
$.unblockUI();
}
},
cache: options.cache,
dataType: "html"
});
}
这个解决方案怎么样,我有一个rules.js,其中包含与元素的所有初始绑定(bind),如果我将它们放入一个函数中,然后在ajax方法的成功回调上调用该函数,这样我不会重复代码...
嗯,请思考一下:D
最佳答案
你可以这样做:
function createPickers(context) {
$(".datefield", context || document).datepicker({
showAnim:'fadeIn',
dateFormat:'dd/mm/yy',
changeMonth:true,
changeYear:true
});
}
要在 document.ready
上运行,如果您已经有 document.ready
函数,您可以调用:
createPickers();
或者你可以在 it's own document.ready
handle 中运行它,像这样:
$(createPickers);
在您的 success
回调中,您可以这样调用它:
createPickers(responseText);
它的作用只是选择 .datefield
在提供的上下文中(内部使用 .find()
),所以 document.ready
您正在选择所有匹配元素来创建日期选择器,但在 ajax 请求中,您仅选择刚刚到达响应中的匹配元素,而不是在任何地方创建重复的日期选择器。
关于binding - jQuery 日期选择器在 AJAX 之后不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2801986/