简体   繁体   English

如何使用jQuery动态按类添加datePicker?

[英]How to add datePicker by class dynamically using jquery?

I am using "jquery-1.9.1.js" and my javascript code is as below: 我正在使用“ jquery-1.9.1.js”,而我的JavaScript代码如下:

$('.fromSearch').on('focus', function(){
var $this = $(this);
  if(!$this.data('datepicker')) {
   $this.removeClass("hasDatepicker");
   $this.datepicker();
   $this.datepicker("show");
  } 
});

my html code is this: 我的html代码是这样的:

<div id="duration" class="duration">
    <td><input type="text" id="fromSearch" class="fromSearch"></td>
</div>

PROBLEM: I am generating "fromSearch" (date picker) dynamically, lets say 5 date pickers, but I get date picker only for the first time! 问题:我正在动态生成“ fromSearch”(日期选择器),可以说是5个日期选择器,但是我第一次才获得日期选择器!

I have been working on solutions provided on similar questions, but none of them is working for me. 我一直在研究针对类似问题的解决方案,但没有一个对我有用。 Can any body help me figuring out where I am going wrong? 有谁能帮助我弄清楚我要去哪里错了? Thanks for your time. 谢谢你的时间。 :) :)

You can try as below: 您可以尝试如下操作:

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

UPDATE 更新

To pass date to a function write onselect event in your datepicker as below: 要将日期传递给函数,请在datepicker写入onselect事件,如下所示:

$('body').on('focus', '.fromSearch', function(){
    $(this).datepicker({
          onSelect: function (dateText, inst) {
                   //do necessary actions
          }
    });
});

Your code seems to work. 您的代码似乎可以正常工作。 You need to ensure you are including jQuery-ui. 您需要确保包含jQuery-ui。 DatePicker does not come bundled with jQuery DatePicker不与jQuery捆绑在一起

http://code.jquery.com/ui/ http://code.jquery.com/ui/

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

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