简体   繁体   English

如何使用on()通过Jquery向动态添加的div中添加日期选择器

[英]How to add a datepicker to a dynamically added div with Jquery with on()

I am adding a div to a form that I am creating. 我将div添加到正在创建的表单中。 I want to do this with the on() function, but I cannot seem to make it work. 我想使用on()函数来执行此操作,但似乎无法使其正常工作。 From what I understand you have to use an event, but is there a way to make an event out of a div being added. 据我了解,您必须使用一个事件,但是有一种方法可以使div中的事件成为现实。 The code that I have been trying is with a "click" event, but that isnt really what I want. 我一直在尝试的代码带有“ click”事件,但这并不是我想要的。 The datepicker is added after the first click, but the buttonImage is not being added at all. 第一次单击后将添加日期选择器,但根本没有添加buttonImage。 I need it to work on the first click. 我需要它才能在第一次点击时起作用。 Here is the code that I am using right now: 这是我现在正在使用的代码:

  $('#switcher-panel').on('click', 'table tr td input', function(){
    $('.datepicker').datepicker({
      buttonImage: "images/calendar.png"
    });
  });

Here is the html that I am using: 这是我正在使用的html:

<table class="table table-hover" data-controller="rank">
  <thead>
    <tr>
      <th colspan="4" align="left"><h2> Boy Scout Rank</h2></th>
    </tr>
    <tr>
      <th>Number</th>
      <th>Requirements</th>
      <th>Completed</th>
      <th>Date</th>
    </tr>
  </thead>
  <tbody>
    <tr data-name="one_li">
      <td>1</td>
      <td>
        Req
      </td>
      <td>
        <input class="datepicker"/>
      </td>
    </tr>
  </tbody>
</table>

I dont understand how to handle this. 我不明白该如何处理。 Any help would be great. 任何帮助都会很棒。

Judging by your above code, it doesn't look like you're adding a new <div /> 从上面的代码来看,您似乎没有添加新的<div />

If you're not, you shouldn't need to add an event (click) handler - http://jsfiddle.net/ZNR7P/ 如果不是这样,则无需添加事件(点击)处理程序-http://jsfiddle.net/ZNR7P/

You should just be able to do: 您应该能够:

$(function() {

    $('.datepicker').datepicker();

});​
$(function(){

    $('.datepicker').datepicker({
        showOn:"button", // or "both" if you want the input to trigger the datepicker too
        buttonImage: "images/calendar.png"
    });

})

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

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