jQuery的自动完成不响应动态插入的元素 [英] jquery autocomplete does not respond to dynamically inserted element

查看:161
本文介绍了jQuery的自动完成不响应动态插入的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在努力与自动完成的jQuery动态插入的元素(做了静态元素自动完成之前)。这里是插在HTML源$ C ​​$ C一自动完成添加元素(有可能插入在同一页上的多个元件)。直到它已被插入插入元件的ID是未知的。的ID有所不同元素的元素:

We are working on autocomplete with dynamically inserted elements with jquery (did autocomplete on static elements before). Here is the html source code for one autocomplete added element inserted (there may be more than one element inserted on the same page). The id of inserted element is unknown until it has been inserted. The ids vary from element to element:

<input type="text" size="50" placeholder="Enter keyword" name="requisition[material_items_attributes][1414037215952][item_name_autocomplete]" id="requisition_material_items_attributes_1414037215952_item_name_autocomplete" data-autocomplete-source="/whs/items/autocomplete" class="string required span5">

下面是JS code为自动完成:

Here is the js code for autocomplete:

$(function() {
   $("[id^='requisition_material_items_attributes_'][id$='_item_name_autocomplete']").each(function (){
      return $(this).autocomplete({
        minLength: 1,
        source: $(this).data('autocomplete-source'),
        select: function(event, ui) {
            $(this).val(ui.item.value);
        }
      });
    });
});

当关键字 item_name_autocomplete 的文本框中输入,没有任何反应。我们发现,JS code的自动完成没有执行,没有匹配的id。什么可能导致不匹配?是不是因为动态元素需要重装之前的比赛(不知道如何在这里使用。对,或者有一些其他的方法可以做到重装)?

When keyword entered in text box of item_name_autocomplete, nothing happens. We found that the js code for autocomplete was not executed and there is no match of the id. What could cause the no match? Is it because the dynamic element needs reloading before match (not sure how to use .on here. or there is some other ways to do the reloading)?

推荐答案

setTimeout的解决了这个问题:

setTimeout solves the problem:

 setTimeout(function(){
  $("[id^='requisition_material_items_attributes_'][id$='_item_name_autocomplete']").each(function (){
        $(this).autocomplete({
        minLength: 1,
        source: $(this).data('autocomplete-source'),
        select: function(event, ui) {
            $(this).val(ui.item.value);
        }
      });
    });
  }, 5000);

这篇关于jQuery的自动完成不响应动态插入的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆