ajax调用后jQuery日历无法正常工作,但是按钮在那里?

时间:2016-10-16 00:26:22

标签: javascript jquery html ajax datepicker

我在这里遇到了JQuery日历的问题,它在ajax调用后无效。我尝试了很多选项,但其中任何一个都有效

这是我的js:

function carregar(metodo, div) {
    var loading = new Image();
    loading.src = "${resource(dir: 'images', file: spinner.gif)}";
    $.ajax({
        url: metodo,
        type: "GET",
        dataType: 'text',
        beforeSend: function () {
            $("#" + div).html(loading);
        },
        success: function (data) {
            $("#" + div).html(data);

        }
    });
}

$(function () {
    $("#nascimento").datepicker({
        showOn: "button",
        buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
        buttonImageOnly: true
    });
});

这是索引,我称之为ajax函数:

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
    <head> 
        <meta name="layout" content="main" />
        <title>Cadastrar Aluno</title>
    </head>
    <body>                
        <input type="button" value="Novo"  onClick="carregar('/aluno/novo', 'divForm')"/> 
        <input type="button" value="Pesquisar"  onClick="carregar('/aluno/pesquisar', 'divForm')"/> 


    <div id="divForm">        
        <g:render template="form"></g:render>
        </div>       
    </body>
</html>

这是我的表单模板:

<asset:javascript src="application.js"/> 
<g:uploadForm controller="aluno" action="salvar">    
    //other fields
    <label>Data de Nascimento:</label>    
    <input type="text" name="nascimento" id="nascimento" required="true" value="<g:formatDate format="dd-MM-yyyy" date="${aluno?.nascimento}"/>"/><br>           
    //other fields
    <input type="submit" value="Salvar"/>
    <input type="button" name="btnCancelar" value="Cancelar"/> 
    <input type="hidden" name="id" value="${aluno?.id}">    
</g:uploadForm>

如果我把

<script type="text/javascript">
    $(function() {
        $( "#nascimento" ).datepicker();
    });
</script>

在模板中,ir工作一次,如果我在重新加载页面后再次加载“表单”模板,则不会。

我试过这个: jquery datepicker doesn't work after ajax call if its already on page JQuery datepicker not working after ajax call jQuery datepicker does not work after Ajax call

你们有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

当您重新加载html时,您正在销毁附加了日期选择器的元素并重新重新创建它。

因此,您需要在替换html后重新初始化datepicker,如下所示:

                 success: function (data) {
                    $("#" + div).html(data);
                    $("#nascimento").datepicker('remove').datepicker({
                        showOn: "button",
                        buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
                        buttonImageOnly: true
                    });

                }