加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

绑定 – 在AJAX之后jQuery日期选择器不持久

发布时间:2020-12-16 02:50:11 所属栏目:百科 来源:网络整理
导读:所以我正在使用jQuery日期选择器,它运行良好.我正在使用 AJAX来获取一些内容,显然当应用这个新内容时,绑定丢失,我 learnt about this last week并发现了.live()方法. 但是如何将其应用到我的日期选择器?因为这不是一个事件因此.live()将无法帮助……对吗?
所以我正在使用jQuery日期选择器,它运行良好.我正在使用 AJAX来获取一些内容,显然当应用这个新内容时,绑定丢失,我 learnt about this last week并发现了.live()方法.

但是如何将其应用到我的日期选择器?因为这不是一个事件因此.live()将无法帮助……对吗?

这是我用来将日期选择器绑定到我的输入的代码:

$(".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,其中包括我对元素的所有初始绑定,如果我将它们放在一个函数中,然后在ajax方法的成功回调上调用该函数,那样我就不会重复代码……

嗯,请问:D

解决方法

你可以这样做:

function createPickers(context) {
  $(".datefield",context || document).datepicker({
    showAnim:'fadeIn',changeYear:true
  });
}

要在document.ready上运行,如果您已经有document.ready函数,则可以调用:

createPickers();

或者您可以在it’s own document.ready handle中运行它,如下所示:

$(createPickers);

在您的成功回调中,您可以这样称呼它:

createPickers(responseText);

这样做只是在提供的上下文中选择.datefield(在内部使用.find()),所以在document.ready你选择所有匹配的元素来创建日期选择器,但在你的ajax请求中,你只选择匹配的元素刚刚到达响应中,没有在任何地方创建重复的日期选择器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读