Javascript 在局部视图中动态加载后如何使 JQuery DatePicker 工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14075312/
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
How to make JQuery DatePicker work after dynamically loaded in a partial view?
提问by Néstor Sánchez A.
I have lost jquery datepicker functionality in this scenario...
在这种情况下,我失去了 jquery datepicker 功能......
1- Originally I had a normal view, which worked fine, having this code for date input...
1-最初我有一个正常的视图,效果很好,有这个用于日期输入的代码......
<input type="text" name="date_start" id="date_start"
value="@(Model.TimeStart)" />
<script language="javascript" type="text/javascript">
$("#date_start").datepicker();
</script>
2- Then, I converted that view in a partial view which is dynamically loaded with...
2-然后,我将该视图转换为动态加载的部分视图...
$('#TargetEmptyDiv').load("/MyController/MyAction");
3- The partial view loads ok, the data can be (manually) entered and all its fine. The only problem is that the jquery datepicker is no longer working. I tryed to assign it after the loading, using this...
3- 局部视图加载正常,数据可以(手动)输入并且一切正常。唯一的问题是 jquery 日期选择器不再工作。我尝试在加载后分配它,使用这个......
$('#TargetEmptyDiv').load("/MyController/MyAction",
function () { $("#date_start").datepicker(); });
That did not work.
那没有用。
4- Later I've learned that jquery provides the live() and delegate() functions which are capable of attach javascript code to elements loaded "now and in the future". So, I tryed this in the document initialization...
4- 后来我了解到 jquery 提供了 live() 和 delegate() 函数,它们能够将 javascript 代码附加到“现在和将来”加载的元素上。所以,我在文档初始化中尝试了这个......
<script type="text/javascript">
$(document).ready(function () {
$("#date_start").live("click", function () { $(this).datepicker(); });
});
</script>
and later also...
后来也...
<script type="text/javascript">
$(document).ready(function () {
$("#date_start").delegate("click", function () { $(this).datepicker(); });
});
</script>
none of which worked, maybe because they directly reference to the "click" event, but the datepicker is "attached" (if that is the proper term) to the whole element.
没有一个工作,也许是因为它们直接引用了“点击”事件,但日期选择器是“附加”到整个元素的(如果这是正确的术语)。
So, question is: How to make the jquery datepicker work on elements loaded after dynamic load???
所以,问题是:如何让 jquery datepicker 处理动态加载后加载的元素???
Thanks for your time!
谢谢你的时间!
SOLVED: The problem was that at the bottom of _Layout.cshtml there is this line...
已解决:问题是在 _Layout.cshtml 的底部有这一行...
@Scripts.Render("~/bundles/jquery")
..which loads the minified version of jquery libraries (already referenced by myself). So, the libraries were loaded twice and got invalid, producing the error "datepicker() is not a function".
..它加载了 jquery 库的缩小版本(我已经引用了)。因此,这些库被加载了两次并且变得无效,产生错误“datepicker() 不是函数”。
Just commenting or deleting that line, makes all work fine!
只需评论或删除该行,一切正常!
回答by Charly
Put the following jQuery in the base view, not the partial view
将以下 jQuery 放在基础视图中,而不是局部视图中
<script>
$(document).ready(function () {
$(document).on('focus', '.datefield', function () {
$(this).datepicker();
});
});
</script>
This will work when a partial view is dynamically loaded and on page load.
当动态加载局部视图和页面加载时,这将起作用。
回答by machineghost
Your approach in #3 looks to me like it should have worked, so it seems like you need to do some debugging. Try this:
您在 #3 中的方法在我看来应该有效,因此您似乎需要进行一些调试。尝试这个:
- Get the Firebug extension, if you use Firefox (Chrome has dev tools built in)
- Add a
debuggerline to your code (see below for example) - Load your page up with Chrome or Firebug/Firefox (or any other browser's dev tools)
- 获取 Firebug 扩展程序,如果您使用 Firefox(Chrome 内置开发工具)
debugger在您的代码中添加一行(例如,请参见下文)- 使用 Chrome 或 Firebug/Firefox(或任何其他浏览器的开发工具)加载您的页面
What should happen is that your browser will pause at that point. However, if things aren't working as you expect, it might not be hitting that code at all, and then you'd get no pause.
应该发生的是,您的浏览器将在此时暂停。但是,如果事情没有像您预期的那样工作,它可能根本不会执行该代码,然后您就不会停顿了。
If you do get a pause, use the console to inspect the value of $("#date_start"); it's possible that jQuery selector isn't grabbing what you think it is.
如果确实暂停,请使用控制台检查$("#date_start");的值。jQuery 选择器可能没有抓住您认为的内容。
Here's a debuggerexample with your code:
这是debugger您的代码示例:
$('#TargetEmptyDiv').load("/MyController/MyAction", function () {
debugger;
$("#date_start").datepicker();
});
回答by Maulik Shah
On your partial page say "/MyController/MyAction",
在您的部分页面上说“/MyController/MyAction”,
Partial Page Code:
部分页面代码:
<div>
<form>
<!--Other Elements-->
<input type="text" id="adate" name="adate" title="date" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$( "#adate" ).datepicker();
});
</script>
</div>
Full Page(Page From Where You are Calling Ajax Request) Code:
整页(从您调用 Ajax 请求的页面)代码:
<div id="TargetEmptyDiv"></div>
<script type="text/javascript">
function abc(){
$.ajax({
type: "POST",
url: "/MyController/MyAction",
success: function(response)
{
$("#TargetEmptyDiv").html(response);
}
});
}
</script>
call function abc and you are done.assuming you already have all jquery files loaded.
调用函数 abc 就完成了。假设您已经加载了所有 jquery 文件。
回答by wecky
In my case, the Id of the date field that I tried to hook up the datepicker to was not what I thought it was. I am using ViewModels and the id got prefixed with the ViewModel name of my partial view.
就我而言,我试图将日期选择器连接到的日期字段的 ID 并不是我认为的那样。我正在使用 ViewModels 并且 id 以我的局部视图的 ViewModel 名称为前缀。
machineghost's answer put me on to it.
machineghost 的回答让我明白了。
So I now use Charly's answer but instead of #BirthDate I have #IdentityModel_BirthDate:
所以我现在使用 Charly 的答案,但我有 #IdentityModel_BirthDate 而不是 #BirthDate:
<script>
$(document).ready(function () {
$(document).on('focus', '#IdentityModel_BirthDate', function () {
$(this).datepicker({
format: 'MM/dd/yyyy',
changeMonth: true,
changeYear: true,
yearRange: "-90:+0"
});
});
});
</script>
回答by del
All you need to make the datepicker work is steps 1-3.
使日期选择器工作所需的只是步骤 1-3。
Here's a sample: http://jsfiddle.net/delrosario/Xd8py/
这是一个示例:http: //jsfiddle.net/delrosario/Xd8py/
You got datepicker to work without loading the markup dynamically and your pseudo code for the dynamic version is sound from steps 1-3. The thing you need to check now is to make sure that your dependencies are being loaded before your main program (in this case make sure that jquery and jquery ui are available before running the request + datepicker setup).
您让 datepicker 在不动态加载标记的情况下工作,并且您的动态版本的伪代码在步骤 1-3 中是合理的。您现在需要检查的是确保您的依赖项在主程序之前加载(在这种情况下,请确保在运行请求 + 日期选择器设置之前 jquery 和 jquery ui 可用)。
1) load jquery 2) load jquery ui 3) wait till the dom is ready or the element that will contain your payload is ready 4) execute your main app that does steps 1-3 from your description.
1) 加载 jquery 2) 加载 jquery ui 3) 等到 dom 准备好或包含您的有效负载的元素准备好 4) 执行您的主应用程序,根据您的描述执行步骤 1-3。
So it would be something like this.
所以它会是这样的。
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="path-jquery-ui-css" />
<script src="path-to-jquery"></script>
<script src="path-to-jquery-ui"></script>
<script id="main_app">
(function () {
// wait till dom is ready before executing our code,
// in this case steps 1-3.
});
</script>
</head>
<body>
<div id="datepicker_target">datepicker target</div>
</body>
</html>
回答by StevoKeano
After invoking ajax, hookup your jquery to the 'ajaxStop' event. (SEE: '@section Scripts' )
调用 ajax 后,将您的 jquery 连接到 'ajaxStop' 事件。(参见:'@section 脚本')
$(document).ajaxStop handles the post ajax jquery call and now datapicker works after ajax call(s). yea...
$(document).ajaxStop 处理 post ajax jquery 调用,现在 datapicker 在 ajax 调用之后工作。是的...
Note:$(document).ready... handles the initial page load datapicker decoration, but after an ajax form reload, datepicker jquery was not executed...
注意:$(document).ready... 处理初始页面加载 datapicker 装饰,但是在 ajax 表单重新加载后,datepicker jquery 没有执行...
@model Q_Admin.Models.AllQAViewModel
<div id="mainContent">
@using (Ajax.BeginForm("EAAll","Answer",new AjaxOptions {
UpdateTargetId = "mainContent",
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace
}))
for (int i = 0; i < Model.VMs.Count; i++)
{
@switch (Model.QAVMs[i].qN.Node1.TypeAnswer.AnswerType.Trim().ToUpper())
{
case "DATETIME":
@Html.TextBoxFor(m => m.VMs[i].CurrentNodeText,
new { @class = "datepicker", @id = "datepicker" });
break;
case "DROPDOWNLIST":
@Html.DropDownListFor(m => m.QAVMs[i].AnswerRecord.AnswerID,
new SelectList(Model.QAVMs[i].answerNodes, "ID", "NodeText.Text", Model.QAVMs[i].SelectedNodeID),
"-- Select an Answer --",
new { @onchange = "$(this).parents('form:first').find(':submit')[0].click();" }) }
break;
default:
break;
}
}
</div>
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
// debugger;
$("#datepicker").datepicker(
{
dateFormat: "mm/dd/yy",
constrainInput: true
});
});
$(document).ajaxStop(function () {
// debugger;
$("#datepicker").datepicker(
{
dateFormat: "mm/dd/yy",
constrainInput: true
});
});
</script>}
回答by user2430858
I had the exact same problem. If using ajax, then bind the below jquery function to the document. Each time ajax is executed, this will fire. Check out the api doc here - http://api.jquery.com/category/ajax/global-ajax-event-handlers/
我有同样的问题。如果使用 ajax,则将下面的 jquery 函数绑定到文档。每次执行 ajax 时,都会触发。在此处查看 api 文档 - http://api.jquery.com/category/ajax/global-ajax-event-handlers/
$(document).ajaxComplete(function (){//your code here})
$(document).ajaxComplete(function (){//你的代码在这里})
回答by Krlos
I had the same problem, solved using a previous version of JQuery-UI. In my case goes to use the version 1.9.2and 1.10.3to JQueryversion 1.10.1. Know the reason, but I think the latest versions bring some problems compactness, so I chose to use always backward to the past.
I hope it will be useful
我遇到了同样的问题,使用以前版本的JQuery-UI. 在我的案子最后使用的版本1.9.2,并1.10.3以JQuery版本1.10.1。知道原因,但我觉得最新的版本带来了一些紧凑性的问题,所以我选择使用总是倒退过去。我希望它会很有用
回答by ijason03
I've had this problem before. In my situation I had <script src='jQueryUI.js'></script>referenced at the bottom of the page. Moving the reference to the top of page fixed it for me.
我以前遇到过这个问题。在我的情况下,我<script src='jQueryUI.js'></script>在页面底部引用了。将参考移动到页面顶部为我修复了它。
回答by A. Wolff
Seems like #3 should works. But maybe you can try a hacky way like this:
似乎#3 应该有效。但也许你可以尝试像这样的hacky方式:
<script type="text/javascript">
$(document).ready(function () {
$(this).on("mousedown", "#date_start", function (e) {
$(this).datepicker(); e.preventDefault();$(this).click();
});
});
</script>

