在动态生成的输入上委派typeahead

时间:2016-08-27 13:43:56

标签: javascript jquery html twitter-bootstrap event-delegation

我有一个html表,我用它来输入库存详情。在这个表中我有一个产品名称的输入框,我在其上绑定了bootstrap的typeahead事件。但问题是第一行输入框它在呈现时已经出现在页面上,typeahead工作正常。但是当我为更多条目添加新行时,typeahead不能用于它们。我知道事件委托的概念但问题是我不是&#39 ;我知道如何在这种情况下实现它。通过这个指导我。 提前致谢。 这是我的html表 -

<table>
<thead>
<tr>
<td>Product name</td>
<td>Amount</td>
</tr>
</thead>
<tbody class="details">
<tr>
<td><input type="text class="items" name="items" id="items" data-provide="typeahead" /> </td>
<td><input type="text" name="amt" id="amt" class="amt" /></td>
</tr>
</tbody>
</table>

这是用于添加新行的javascript -

$(function(){
  $('#add').click(function(){
    addnewrow();
  });
});
function addnewrow(){
 var tr = '<tr>'+
'<td><input type="text" name="items" id="items" class="items" data-provide="typeahead" autocomplete="off" /></td>'+
'<td><input type="text" name="amt" id="amt" class="amt" autocomplete="off" /></td>'+
'</tr>';
$('.details').append(tr);
}

以下是我如何使用typeahead -

 $(function(){
    $('#items').typeahead({
  source: function(query,process){
    $.ajax({
         url: 'itemexist.php',
         type: 'POST',
         data: 'query=' +query,
         dataType: 'JSON',
         async: true,
         success: function(data){
          process(data);
         }
    });
  }

  });
});

我知道之前已经问过这个问题,但是没有可接受的解决方案,我尝试过这些解决方案,但它没有用。 这是我尝试过的,但它似乎没有用 -

$(document).on("keypress",".items",function(){
 $('.items').typeahead({
  source: function(query,process){

    $.ajax({
         url: 'itemexist.php',
         type: 'POST',
         data: 'query=' +query,
         dataType: 'JSON',
         async: true,
         success: function(data){
          process(data);
         }
    });
  }

  });
 });

1 个答案:

答案 0 :(得分:1)

嗯,我实现了这个......我发布这个,这样可以帮助其他人 这是解决方案 -

 $(function(){
 $('body').delegate('.items','focus',function(){
 $(this).typeahead({
  source: function(query,process){

    $.ajax({
         url: 'itemexist.php',
         type: 'POST',
         data: 'query=' +query,
         dataType: 'JSON',
         async: true,
         success: function(data){
          process(data);
         }
    });
  }

  });
 });
  });
相关问题