简体   繁体   English

jquery datepicker不能动态创建html

[英]jquery datepicker not working on dynamically created html

I'm creating dynamically a couple of div with inner controls. 我正在用内部控件动态创建几个div。 Two of those controls should be datepickers. 其中两个控件应该是datepickers。 But for some reason they are not showing (only input text are shown) It works if I create static html, but not when I'm using dynamic one. 但由于某种原因,它们没有显示(只显示输入文本)如果我创建静态html,它会起作用,但是当我使用动态html时则不行。

This is the code I'm using to generate the HTML (I can see the div) 这是我用来生成HTML的代码(我可以看到div)

var ShowContainerDiv = document.createElement('DIV');

var btnShowDiv = document.createElement('DIV');
btnShowDiv.id = 'btnShowDiv ';
btnShowDiv.title = 'Change';
btnShowDiv.index = 120;

var lblShow = document.createElement('label')
lblShow.htmlFor = "btnShowDiv";
lblShow.appendChild(document.createTextNode('Show'));
btnShowDiv.appendChild(lblShow );
btnShowDiv.onclick = function () {
    dropdown.style.visibility = "visible";
};

var dropdown = document.createElement('DIV');
dropdown.style.backgroundColor = 'white';
dropdown.style.borderStyle = 'solid';
dropdown.style.borderWidth = '2px';
dropdown.style.cursor = 'pointer';
dropdown.style.textAlign = 'left';
dropdown.style.width = '150px';

var chkRed = document.createElement("input");
chkRed.type = "checkbox";
chkRed.id = "chkRed";
chkRed.value = "Red";
chkRed.checked = false;
var lblRed = document.createElement('label')
lblRed.htmlFor = "chkRed";
lblRed.style.color = "#F00";
lblRed.appendChild(document.createTextNode('Red'));

var chkYellow = document.createElement("input");
chkYellow.type = "checkbox";
chkYellow.id = "chkYellow";
chkYellow.value = "Yellow";
chkYellow.checked = false;
var lblYellow = document.createElement('label')
lblYellow.htmlFor = "chkYellow";
lblYellow.style.color = "#FF0";
lblYellow.appendChild(document.createTextNode('Yellow'));

var chkGreen = document.createElement("input");
chkGreen.type = "checkbox";
chkGreen.id = "chkGreen";
chkGreen.value = "Green";
chkGreen.checked = false;
var lblGreen = document.createElement('label')
lblGreen.htmlFor = "chkGreen";
lblGreen.style.color = "#0F0";
lblGreen.appendChild(document.createTextNode('Green'));

var dateFrom = document.createElement("input");
dateFrom.id = "txtDateFrom";
dateFrom.type = "text";
dateFrom.className = "datepicker";
dateFrom.style.width = "70px";
dateFrom.readonly = "readonly";
var lblDateFrom = document.createElement('label')
lblDateFrom.htmlFor = "txtDateFrom";
lblDateFrom.appendChild(document.createTextNode('From'));

var dateTo = document.createElement("input");
dateTo.id = "txtDateTo";
dateTo.type = "text";
dateTo.className = "datepicker";
dateTo.style.width = "70px";
dateTo.readonly = "readonly";
var lblDateTo = document.createElement('label')
lblDateTo.htmlFor = "txtDateTo";
lblDateTo.appendChild(document.createTextNode('To'));

var btnDone = document.createElement("input");
btnDone.type = "button";
btnDone.name = "btnDone";
btnDone.value = "Done";
btnDone.onclick = function () {
    dropdown.style.visibility = "hidden";
};

dropdown.appendChild(chkRed);
dropdown.appendChild(lblRed);
dropdown.appendChild(document.createElement("BR"));
dropdown.appendChild(chkYellow);
dropdown.appendChild(lblYellow);
dropdown.appendChild(document.createElement("BR"));
dropdown.appendChild(chkGreen);
dropdown.appendChild(lblGreen);
dropdown.appendChild(document.createElement("BR"));
dropdown.appendChild(dateFrom);
dropdown.appendChild(document.createElement("BR"));
dropdown.appendChild(dateTo);
dropdown.appendChild(document.createElement("BR"));
dropdown.appendChild(btnDone);

ShowContainerDiv.appendChild(btnShowDiv);
ShowContainerDiv.appendChild(dropdown);

g.event.addDomListener(btnShowDiv, 'click', function () {
    dropdown.visible = true;
    dropdown.style.visibility = "visible";
});

g.event.addDomListener(btnDone, 'click', function () {
    dropdown.visible = false;
    dropdown.style.visibility = "hidden";
});

map.controls[g.ControlPosition.TOP_RIGHT].push(ShowContainerDiv);

Then in a .js file I have this (I checked and I'm including the file) 然后在.js文件中我有这个(我检查过,我包含了文件)

$(document).ready(function () {
    $(".datepicker").datepicker({
        dateFormat: 'yy/m/d',
        firstDay: 1,
        changeMonth: true,
        changeYear: true,
        showOn: 'both',
        autosize: true,
        buttonText: "Select date",
        buttonImage: '../Content/images/calendar.png',
        buttonImageOnly: true
    });
});

Why the datepicker is not showing up? 为什么日期选择器没有出现? Thanks! 谢谢! Guillermo. 吉列尔莫。

When you write 当你写作

$(document).ready(function () {
    $(".datepicker").datepicker({...});
});

This fragment is getting executed right after the page has loaded. 该片段在页面加载后立即执行。 Therefore, your dynamic datepickers are not there yet. 因此,您的动态日期选择器还没有。 You need to call $(aSuitableSelector).datepicker(...) on each newly-inserted element. 您需要在每个新插入的元素上调用$(aSuitableSelector).datepicker(...) First, use a var to hold your options: 首先,使用var来保存您的选项:

var datePickerOptions = {
    dateFormat: 'yy/m/d',
    firstDay: 1,
    changeMonth: true,
    changeYear: true,
    // ...
}

This allows you to write 这允许你写

 $(document).ready(function () {
    $(".datepicker").datepicker(datePickerOptions);
 });

and to write 并写

 // right after appending dateFrom to the document ...
 $(dateFrom).datepicker(datePickerOptions);

 //...

 // right after appending dateTo ...
 $(dateTo).datepicker(datePickerOptions);

You can also use JQuery's ability to listen to DOM changes to avoid having to apply JS magic to newly-inserted elements -- but I do not think it is worth it. 您还可以使用JQuery的能力来监听DOM更改,以避免将JS魔法应用于新插入的元素 - 但我认为这不值得。

The easiest way I found to add datepicker for dynamically added multiple input field: 我发现添加datepicker以动态添加多个输入字段的最简单方法:

    $('body').on('focus',".datepicker", function(){
        $(this).datepicker();
    });

The easiest way I found to fix this issue is by using the livequery plugin: 我发现解决此问题的最简单方法是使用livequery插件:

http://docs.jquery.com/Plugins/livequery http://docs.jquery.com/Plugins/livequery

Instead of applying the datepickers to all objects of a specific class, you tell LiveQuery to apply it to those objects. 您可以告诉LiveQuery将其应用于这些对象,而不是将日期选择器应用于特定类的所有对象。 LiveQuery will in turn keep applying the datepicker, even when your DOM is changed later on. 即使以后更改了DOM,LiveQuery也会继续应用 datepicker。

I have seen no performance drops when usnig this, and the code changes are really minimal (you need to add the plugin to the page and only change one line of code). 我发现在使用它时没有性能下降,代码更改实际上是最小的(您需要将插件添加到页面中,只更改一行代码)。

You would be using it like so: 你会像这样使用它:

$(".datepicker").livequery(
        function(){ 
            // This function is called when a new object is found. 
            $(this).datepicker({ ...}});
        }, 
        function() { 
            // This function is called when an existing item is being removed. I don't think you need this one so just leave it as an empty function.
        }
); 

From then on, every time you add an object with the datepicker class, the datepicker plugin will automatically be applied to it. 从那时起,每次使用datepicker类添加对象时,datepicker插件都会自动应用于它。

You can simply use this. 你可以简单地使用它。

$('body').on('focus',".date-picker", function(){
  $(this).datepicker();
});

The code that bind the datepickers is best to be executed right after your html is dinamically created. 绑定日期选择器的代码最好在你的html被动态创建之后执行。 If you want to keep the code for datepicker initialization in a separate file, I would recommend the following approach: After you finish generating your html (I presume it is generated on document ready), use 如果你想将datepicker初始化的代码保存在一个单独的文件中,我建议采用以下方法:在你完成生成html之后(我认为它是在文档就绪时生成的),使用

$(document).trigger("customHtmlGenerated");

And in the datepicker file, instead of $(document).ready(function(){...}) use $(document).bind("customHtmlGenerated", function(){...}); 在datepicker文件中,而不是$(document).ready(function(){...})使用$(document).bind("customHtmlGenerated", function(){...});

I put the 我把它

$( "#InstallDate" ).datepicker({
  showOn: "button",
    minDate: 0, // no past dates
  buttonImage: "../images/Date.png",
  buttonImageOnly: true,
  buttonText: "Select date",
  dateFormat: 'yy-mm-dd',
}); 

into a script file DatePicker.js and then added the following line at the end of my generated Ajax Html form 到一个脚本文件DatePicker.js,然后在我生成的Ajax Html表单的末尾添加以下行

<script type='text/javascript' src='/inc/DatePicker.js'></script> 
$( ".datepicker" ).datepicker({inline: true,dateFormat: "dd-mm-yy"});

Please add below code after appending element. 请在追加元素后添加以下代码。

$(".datepicker").datepicker({
        dateFormat: 'yy/m/d',
        firstDay: 1,
        changeMonth: true,
        changeYear: true,
        showOn: 'both',
        autosize: true,
        buttonText: "Select date",
        buttonImage: '../Content/images/calendar.png',
        buttonImageOnly: true
    });

The jQuery code is executed when the document is ready: this means when the initial markup of your page is ready, not after your javascript files ran. 文档准备就绪时执行jQuery代码:这意味着页面的初始标记准备就绪,而不是在运行javascript文件之后。

I suppose your code to initialize the datepickers runs before your script creating the elements does, so nothing happens. 我想你的代码初始化datepickers运行创建元素的脚本之前运行,所以没有任何反应。


Try executing you jquery code when the page has loaded using .load() instead of .ready(). 使用.load()而不是.ready()加载页面时尝试执行jquery代码。 The load event is fired when all assets (js, image...) have loaded. 加载所有资产(js,image ...)时会触发load事件。

$(window).load(function () {
    $(".datepicker").datepicker({
        ...
    });
});

You could also simply use the way javascript is executed. 您也可以简单地使用javascript的执行方式。 Scripts are executed in the order they happen in the page. 脚本按照它们在页面中发生的顺序执行。 So you could: 所以你可以:

  • move your scripts right before the closing body tag ``` 在结束体标记```之前移动你的脚本
  • make sure your first script (creating the elements) comes before the datepicker code 确保你的第一个脚本(创建元素)出现在datepicker代码之前
  • remove the .ready() handler for the date picker. 删除日期选择器的.ready()处理程序。 When you place your script at the end, they are implicitly running when the DOM is ready... 当您将脚本放在最后时,它们在DOM准备就绪时隐式运行...

It's probably a matter of in which order the javascript is being fired. 这可能是javascript被解雇的顺序问题。 Try putting 试试看

$(".datepicker").datepicker({
    dateFormat: 'yy/m/d',
    firstDay: 1,
    changeMonth: true,
    changeYear: true,
    showOn: 'both',
    autosize: true,
    buttonText: "Select date",
    buttonImage: '../Content/images/calendar.png',
    buttonImageOnly: true
});

After your javascript that creates the html. 在你的javascript创建html之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM