如何在多个 div 元素和上下文中初始化 typeahead.js?

How to initialize typeahead.js on multiple div element and contextually?

出于各种原因,我需要能够根据上下文复制输入框。每次用户添加另一个行程时,如何初始化另一个 typeahead.js 实例?我似乎无法在 .on()

中初始化它

这是我当前的代码:

html:

<form>
    <div class="summary">
        <div class="trip">
          <input class="state tt-input">
          ... other code ...
        </div>
        ...
    </div>
    <button type="button" id="add">Add another trip</button>
</form>

jquery:

$(document).ready(function() {

  var additional = $('.trip').html();

  $('form').on("change", '.state', function(e){
      var $contextualDiv = $(e.target).closest('div');
      var $state = $contextualDiv.find('.state');
  });

  $('#add').click(function() {
    if ($('.summary').children().length >= 5) return;
    $('.summary').append('<div class="trip">' + additional + "<div>");
  });

  $('.state').typeahead( //or $state.typeahead (that doesn't seem to work)
     {
        hint: true,
        highlight: true,
        minLength: 1
     },
     {
        name: 'states',
        source: bh,
      });
});

我建议创建一个函数来设置给定实例的提前输入。 然后为每个新创建的实例调用该函数。

$(document).ready(function() {

  var additional = $('.trip').html();


  $('#add').click(function() {
    if ($('.summary').children().length >= 5) return;
    var new_trip = $('<div class="trip">' + additional + "<div>")
    $('.summary').append(new_trip);
    var state = new_trip.find('.state')
    setupState(state)
  });

  setupState($('.state'))
});

function setupState(state){
    state.typeahead(
     {
        hint: true,
        highlight: true,
        minLength: 1
     },
     {
        name: 'states',
        source: bh,
      });
}