jQuery datepicker 只工作一次,第二次不显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16076304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:20:59  来源:igfitidea点击:

jQuery datepicker only works once and is not shown the second time

jqueryjquery-uidatepicker

提问by Gorgsenegger

ASP.NET MVC3 / jQuery 1.9.1 / jQuery UI 1.10.2

ASP.NET MVC3 / jQuery 1.9.1 / jQuery UI 1.10.2

I've got a page on which I open a modal dialog after clicking on an Ajax.ActionLink. Inside this dialog I have an input field and a datepickerassociated with it. When I open the dialog for the first time, I can click on the datepicker button (or inside the associated input field so it receives focus, showOnis set to both), and the datepicker shows as expected. I can, while the modal dialog is open, do it as often as I want to, the datepicker shows every time. When I close the modal dialog (via an attached $("ui-widget-overlay").click(function(){...});and then open it again, the datepicker no longer works, no matter whether I try to click on the button or into the associated input field.

我有一个页面,单击Ajax.ActionLink. 在这个对话框中,我有一个输入字段和一个datepicker与之关联的字段。当我第一次打开对话框时,我可以点击日期选择器按钮(或在相关的输入字段内,以便它接收焦点,showOn设置为both),日期选择器按预期显示。我可以,当模态对话框打开时,按我想要的频率执行,日期选择器每次都会显示。当我关闭模式对话框时(通过附加的$("ui-widget-overlay").click(function(){...});然后再次打开它,日期选择器不再起作用,无论我是尝试单击按钮还是进入相关的输入字段。

I tried to debug the jQuery code, and both times the lines of code being run are the same (and even though the datepicker doesn't show up the second time the dialog is opened, the jQuery methods are triggered) from what I can see in the debugger. I'm completely stumped, and the methods described in this postonly helped in terms of being to show the datepicker the first time the dialog opens. Another postonly seems to be related to a misunderstanding how the showOnsetting works.

我试图调试 jQuery 代码,并且两次运行的代码行都是相同的(即使第二次打开对话框时日期选择器没有出现,jQuery 方法也被触发)从我所看到的在调试器中。我完全被难住了,这篇文章中描述的方法仅有助于在对话框第一次打开时显示日期选择器。另一篇文章似乎只与对showOn设置如何工作的误解有关。

I also tried to destroy the datepicker via $("#datepicker").datepicker("destroy");when closing the dialog - to no avail. Any ideas?

我还尝试$("#datepicker").datepicker("destroy");在关闭对话框时通过销毁日期选择器- 无济于事。有任何想法吗?

Update

更新

On the "calling page":

在“呼叫页面”上:

$(document).ready(function () {
    $("#popupDialog").dialog(
    {
        autoOpen: false,
        modal: true,
        open: function()
        {
            $("ui-widget-overlay").click(function()
            {
                $("#popupDialog").dialog("close");
            }
        }
    });
});
[...]
@Ajax.ActionLink( "Some text", "Action", "Controller", new AjaxOptions {
    HttpMethod = "GET",
    UpdateTargetId = "popupDialog",
    InsertionMode = InsertionMode.Replace,
    OnSuccess = "openPopup()"
})
[...]
function openPopup()
{
    $("popupDialog").dialog("open");
}
[...]
<div id="popupDialog" style="display: none;"></div>

The controller action is very simple and as follows:

控制器动作非常简单,如下所示:

public ActionResult Action()
{
    MyActionModel myActionModel = new MyActionModel();
    return PartialView( myActionModel );
}

回答by Gorgsenegger

After more debugging and attempts to trace jQuery events, I tested whether the problem existed with jQuery UI 1.9.2, which it didn't. Then I compared the relevant datepickercode lines which did not involved too many actual changes.

经过更多的调试和尝试跟踪 jQuery 事件后,我测试了 jQuery UI 1.9.2 是否存在问题,但事实并非如此。然后我比较了相关的datepicker代码行,没有涉及太多实际更改。

To put a long story short, the problem described in my question above could be fixed by changing a single line of code back from 1.10.2 to what it was in 1.9.2:

长话短说,我上面的问题中描述的问题可以通过将一行代码从 1.10.2 改回 1.9.2 来解决:

1.10.2 causing problems

1.10.2 引起问题

/* Initialise the date picker */
if (!$.datepicker.initialized) {
    $(document).mousedown($.datepicker._checkExternalClick);
    $.datepicker.initialized = true;
}

1.9.2. version, working as expected

1.9.2. 版本,按预期工作

/* Initialise the date picker */
if (!$.datepicker.initialized) {
    $(document).mousedown($.datepicker._checkExternalClick)
        // !!!!!!!!!!
        // The next code line has to be added again so that the date picker
        // shows up when the popup is opened more than once without reloading
        // the "base" page.
        // !!!!!!!!!!
        .find(document.body).append($.datepicker.dpDiv);
    $.datepicker.initialized = true;
}

I'm still not sure why this behaviour exists, but it seems to be a relatively rare constellation. As a note: I didn't "reinitialize" the datepickerafter opening the popup dialog (or requesting the PartialViewvia AJAX), so having a single script source as part of the _Layout.cshtmlis sufficient. Hope this helps someone else.

我仍然不确定为什么会存在这种行为,但它似乎是一个相对罕见的星座。请注意:datepicker在打开弹出对话框(或PartialView通过 AJAX请求)之后,我没有“重新初始化” ,因此将单个脚本源作为其中的一部分_Layout.cshtml就足够了。希望这对其他人有帮助。

回答by Giuseppe Abbracciavento

I had the same problem, and I solved with

我有同样的问题,我解决了

$("#ui-datepicker-div").remove();

after closing and destroying the popup.

关闭并销毁弹出窗口后。

回答by Vandesh

What worked for me was -

对我有用的是 -

Inside the dialog, if I have multiple inputs with class datepicker, then

在对话框内,如果我有多个输入 class datepicker,那么

$(".datepicker").removeClass('hasDatepicker').datepicker();  

Basically, to remove the class hasDatepickerbefore initializing datepickeragain.

基本上,hasDatepickerdatepicker再次初始化之前删除类。

I was on version 1.8.18of jquery.ui.datepicker

我在jquery.ui.datepicker1.8.18

回答by bipen

It is opened via an Ajax.ActionLink which updates a target id (div) via the UpdateTargetId property. The controller action returning the contents for the modal dialog queries a web service and then returns a partial view with a populated model.

它通过 Ajax.ActionLink 打开,它通过 UpdateTargetId 属性更新目标 ID (div)。返回模态对话框内容的控制器操作会查询 Web 服务,然后返回带有填充模型的部分视图。

then you need to call the datepciker function againafter the partial view is populated... inside callback function of ajax(if you are using that)...

那么你需要在填充局部视图后再次调用 datepciker 函数......在ajax的回调函数中(如果你正在使用它)......

 $.ajax({
    success:function(){
        //your stuff
       $("#datepicker").datepicker();
     }
 });

datepikcker won't be able to call a function for dynamically added element... since your target div is not present at the time when the datepicker is first called... you need to call the datepicker function again for if to work for added target DIV

datepikcker 将无法为动态添加的元素调用函数......因为在第一次调用 datepicker 时你的目标 div 不存在......你需要再次调用 datepicker 函数来确定是否添加目标 DIV

updated

更新

  OnSuccess = "openPopup()"
  .....

 function openPopup(){
   //your codes
    $("#datepicker").datepicker(); //call date picker function to the added element again
}

回答by DaniCE

I had a similar problem, but what happened to me was that the second time the dialog was loaded, the datapicker didn′t take the value.

我有一个类似的问题,但发生在我身上的是第二次加载对话框时,数据选择器没有取值。

The problem was that I was loading a second time the dialog and these cause problems. The solution was to remove the dialog after close it, something like:

问题是我第二次加载对话框,这些会导致问题。解决方案是在关闭对话框后删除对话框,例如:

  $("#popupDialog").dialog("close");    
  $("#popupDialog").remove();

I hope this helps anyone!

我希望这可以帮助任何人!

回答by Sunny

You can do this by adding a new function to div onclick="focusBlur()"

您可以通过向 div onclick="focusBlur()"添加一个新函数来完成此操作

<script>
    function focusBlur() {
        $('input').blur();
    }
</script>

回答by Andre Gomes

If you need to show more than one time in the same view the calender and it only show's one time try this:

如果您需要在同一视图中多次显示日历并且它只显示一次,请尝试以下操作:

document.getElementById("div_Validade").onclick = function () { SetZIndex() };

function SetZIndex() {
    document.getElementById("ui-datepicker-div").style.zIndex = "999999";
}

div_Validadecorresponds to the div id where the input is placed,

div_Validade对应于放置输入的 div id,

ui-datepicker-divis infragistics element that is not shown.

ui-datepicker-div是未显示的基础设施元素。

回答by Jigar Tanna

initialize the datepicker on ajax success method.

在 ajax 成功方法上初始化日期选择器。

回答by user5512898

btw i will try to explain the way i solved it, cause i think is easier this way.

顺便说一句,我将尝试解释我解决它的方式,因为我认为这种方式更容易。

im not an expert in this matters, so forgive me if I do not use the correct terms to explain it.

我不是这方面的专家,所以如果我没有使用正确的术语来解释它,请原谅我。

if u have 2 places in the same page u want to load datepicker, u got to duplicate the function:

如果您在同一页面中有 2 个地方要加载日期选择器,则必须复制该功能:

$(function() {
    $( "#datepicker" ).datepicker({
      showOn: "button",
      buttonImage: "images/calendar.png",
      buttonImageOnly: true,
      buttonText: "Select date",
      addClass:".ccCFcalV2"
    });    
});       

$(function() {
    $( "#datepicker2" ).datepicker({
      showOn: "button",
      buttonImage: "images/calendar.png",
      buttonImageOnly: true,
      buttonText: "Select date",
      addClass:".ccCFcalV2"
    });
});

and add the class "datepicker2" to the second place u want to call the datepicker. it works, almost for me

并将类“datepicker2”添加到您要调用日期选择器的第二个位置。它有效,几乎对我来说

Hope it helps someone, if u consider this a dumb solution, let me know and i'll remove it

希望它可以帮助某人,如果您认为这是一个愚蠢的解决方案,请告诉我,我会删除它

have a nice day!

祝你今天过得愉快!

回答by Rudresh Ajgaonkar

I wanted to re-inititalise the date picker after modal close as the values selected during the first trial for setting of the dates were still there. So i dont know why but the following code doesnt work for me.

我想在模式关闭后重新初始化日期选择器,因为在第一次试验中选择的用于设置日期的值仍然存在。所以我不知道为什么,但以下代码对我不起作用。

$(selector).datepicker("refresh") 

The above line mentioned in the documentation didnt help!.

文档中提到的上述行没有帮助!。

Following is something which i tried, i.e to destroy and reinititalise the date picker objects.

以下是我尝试过的内容,即销毁并重新初始化日期选择器对象。

$('#addPromoModal').on('hide.bs.modal', function(event) {
$("#startDate").datepicker("destroy");
$("endDate").datepicker("destroy");
initialiseDataPicker(); }

Here is my initialise function :

这是我的初始化函数:

function initialiseDataPicker(){

 $( "#startDate" ).datepicker({
    defaultDate: "+1w",
    showWeek: true,
    firstDay: 1,
    changeMonth: true,
  //  numberOfMonths: 3,
   onClose: function( selectedDate ) {
     $( "#endDate" ).datepicker( "option", "minDate", selectedDate );
   }
 });
 $( "#endDate" ).datepicker({
     defaultDate: "+1w",
    showWeek: true,
    firstDay: 1,
    changeMonth: true,
  //  numberOfMonths: 3,
   onClose: function( selectedDate ) {
     $( "#startDate" ).datepicker( "option", "maxDate", selectedDate );
   }
 });
 }

Hope That helps! RA

希望有帮助!RA