如何将datepicker绑定到dynaimcally添加的元素

时间:2016-11-29 14:31:28

标签: javascript jquery html jquery-ui-datepicker

我无法弄清楚如何在下面的小提琴示例中添加事件处理程序以动态添加html。通过搜索,我意识到你必须将处理程序委托给页面上最初的元素。但是,我将新添加的元素传递给一个设置所有内容的模块(dateTimeRangeWidget)。

https://jsfiddle.net/burtonrhodes/u2L2epmz/

HTML

<h3>
  Date Picker Test
  <a href="#" id="do_addEvent" class="btn btn-warning pull-right">
    Add Event
  </a>
</h3>
<hr/>

<form>

  <div class="eventsDiv">

    <!-- Event[0] -->
    <div class="eventDiv" data-id="0">
      <div class="row">
        <div class="form-group col-xs-3">
          <label>Start Date</label>
          <input type="text" name="event[0].startDate" class="form-control startDate">

          <div class="checkbox">
            <label>
              <input type="checkbox" name="event[0].allDayEvent" class="allDayEvent" /> 
              All Day Event
            </label>
          </div>
        </div>

        <div class="form-group col-xs-3 timeDiv">
          <label>Start Time</label>
          <input type="text" name="event[0].startTime" class="form-control startTime">
        </div>
        <div class="form-group col-xs-3">
          <label>End Date</label>
          <input type="text" name="event[0].endDate" class="form-control endDate">
        </div>

        <div class="form-group col-xs-3 timeDiv">
          <label>End Time</label>
          <input type="text" name="event[0].endTime" class="form-control endTime">
        </div>
      </div>
      <hr/>
    </div>

  </div>
  <!-- ./eventsDiv -->
</form>

JS

$(document).ready(function() {

  // Wire do_addEvent button
  $("#do_addEvent").on("click", function(event) {

    // Copy and add evenDiv html at the bottom
    var lastEventDiv = $("div.eventDiv").last();
    var newEventDiv = $(lastEventDiv).after($(lastEventDiv).html());

    // TODO rename input variable names here with newId
    // --- code here --

    // Setup the new eventDiv
    // !!! This doesn't work !!!
    setUpEventDiv(newEventDiv);

    event.preventDefault();
  });

  // Setup all eventDiv's when the page loads
  $("div.eventDiv").each(function(index, eventDiv) {
    // Wire the eventDiv
    setUpEventDiv(eventDiv)
  });

});

/**
 * Finds all the div elements and calls setupDateTimePicker
 */
function setUpEventDiv(eventDiv) {
  var $startDateTextBox = $(eventDiv).find('.startDate:first').datepicker();
  var $endDateTextBox = $(eventDiv).find('.endDate:first');
  var $startTimeTextBox = $(eventDiv).find('.startTime:first');
  var $endTimeTextBox = $(eventDiv).find('.endTime:first');

  var $allDayEventCheckBox = $(eventDiv).find('.allDayEvent:first');
  var $timesDiv = $(eventDiv).find('.timeDiv');

  // Setup time picker
  setupDateTimePicker($startDateTextBox, $startTimeTextBox,
    $endDateTextBox, $endTimeTextBox,
    $allDayEventCheckBox, $timesDiv);
}

/**
 * Sets up the custom date/time picker widget
 */
function setupDateTimePicker($startDate, $startTime,
  $endDate, $endTime,
  $allDayEvent, $timesDiv) {

  var mydtrw = dateTimeRangeWidget(jQuery);
  mydtrw.init({
    $startDateElem: $startDate,
    $endDateElem: $endDate,
    $startTimeElem: $startTime,
    $endTimeElem: $endTime,
    $allDayEventElem: $allDayEvent,
    $timeElements: $timesDiv
  });
}

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误。

当您执行此操作$(lastEventDiv).html()时,您实际上正在剥离父html元素,因此您始终只有一个.eventDiv

这是working fiddle

$(document).ready(function() {

  // Wire do_addEvent button
  $("#do_addEvent").on("click", function(event) {

    // Copy and add eventDiv html at the bottom
    var lastEventDiv = $("div.eventDiv").last();
    var newEventDiv = lastEventDiv.clone(); //clone the last event div. When you were adding it with .html(), you were removing the parent tags so you never had a second .eventDiv.

    var newId = $("div.eventDiv").length; //lets get a unique ID. This should change in your code for something better.
    newEventDiv.data('id', newId); //change id

    //change the id and name atributes for it to work correctly
    $.each(newEventDiv.find('input'), function(index, element) {
        $(element).attr('id', 'input' + Math.round(Math.random()*100));
      $(element).attr('name',$(element).attr('name').replace(/\[\d+](?!.*\[\d)/, '[' + newId + ']'));
      $(element).removeClass('hasDatepicker'); //remove the hasDatepicker class for the plugin to work correctly.
    })

    lastEventDiv.after(newEventDiv); //append id after the last event div

    // TODO rename input variable names here with newId
    // --- code here --

    // Wire the new eventDiv date/time picker
    // !!! This doesn't work !!!

    setUpEventDiv(newEventDiv);

    event.preventDefault();
  });

  // Loop through event divs and wire actions for each section
  $("div.eventDiv").each(function(index, eventDiv) {
    // Wire the eventDiv
    setUpEventDiv(eventDiv)
  });

});