简体   繁体   English

如何将typeahead.js(Bloodhound)添加到jQuery动态创建的字段中?

[英]How do I add typeahead.js (Bloodhound) to jQuery dynamically-created fields?

I can load Twitter typeahead just fine on a static form. 我可以在静态表单上提前加载Twitter typea。 However, in this situation, I would like to apply it to a dynamically-generated field. 但是,在这种情况下,我想将其应用于动态生成的字段。 Even though my duplication script adds the required ".typeahead" class to the new input, it never seems to work. 即使我的复制脚本将必需的“ .typeahead”类添加到了新输入中,它也似乎无法正常工作。 Indeed, the static form is surrounded by several additional classes, which are not generated for the dynamic fields. 实际上,静态形式被几个其他类包围,这些类不是为动态字段生成的。

I feel like there is something more I need to do in order for the dynamic fields to function like the static field, but I am not sure. 我觉得我需要做更多的工作才能使动态字段像静态字段一样起作用,但是我不确定。

The Javascript: Javascript:

<!-- Dataset: First Names -->
var firstnames = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 5,
    prefetch: {
        url: './datasets/firstnames.json',
        filter: function(list) {
            return $.map(list, function(firstname) { return { name: firstname }; });
        }
    }
});

firstnames.initialize();

$('.typeahead').typeahead(null, {
    name: 'firstnames',
    displayKey: 'name',
    source: firstnames.ttAdapter()
});
<!-- Dataset: First Names (End) -->

<!-- Dynamic Fields -->
var count=2;
$("#add").click(function(){
    var html="<div id='div"+count+"'><input id='firstname"+count+"' type='text' class='typeahead' placeholder='Additional First Name'></input><button type='button' onclick=remover('"+count+"')>Remove</button></div>";
$("#additionalnames").append(html);

    count++;
});

function remover(which){
  $("#div"+which).remove();
}
<!-- Dynamic Fields End -->

The HTML: HTML:

<p>Standard field works fine (type a letter from a to g):</p>
<input type="text" id="firstname" name="firstname" class="typeahead" placeholder="First Name">
<br /><br /><br /><br /><br /><br />
<p>Dynamic field does not:</p>
<div id="additionalnames"></div>
<button id="add" type="button">Add Another</button>

I don't think JSFiddle can handle my json file, so a live implementation is here: http://drjoeseriani.com/firstnames 我认为JSFiddle无法处理我的json文件,因此可以在此处进行实时实现: http ://drjoeseriani.com/firstnames

A downloadable version of this resides here: http://drjoeseriani.com/firstnames.zip 可下载的版本位于这里: http : //drjoeseriani.com/firstnames.zip

Thanks for any help. 谢谢你的帮助。

Creating elements using javascript instead of appending raw markup can be useful. 使用javascript创建元素而不是附加原始标记可能会很有用。 Why ? 为什么呢

Because if you create an element using javascript (or jQuery), you can attach an event/plugins to it and in this case it can be a typeahead plugin. 因为如果您使用javascript(或jQuery)创建元素,则可以将事件/插件附加到该元素,在这种情况下,它可以是预输入插件。

Like this 像这样

var input = $('<input>').attr('id', 'firstname' + count).addClass('typeahead').prop('placeholder', 'Additional First Name');

Now that you have an input element you can attach .typehead({ ... }) to it. 现在您有了输入元素,可以将.typehead({ ... })附加到它。

So your click event should be something like this. 因此,您的点击事件应该是这样的。

$("#add").click(function() {
  // creating a new <div id=count></div>
  var div = $('<div>').attr('id', count);

  // creating a new <input id=count class="typeahead" placeholder=".."></input> 
  var input = $('<input>').attr('id', 'firstname' + count)
    .addClass('typeahead')
    .prop('placeholder', 'Additional First Name');

  // creating a new <button>Remove</button> (with a click event)
  var button = $('<button>').text('Remove')
    .on('click', function() {
      $(this).closest('div').remove();
    });

  div.append(input); // appending the input to the div
  div.append(button); // appending the button to div

  // attaching typeahead to the newly creating input
  input.typeahead(null, {
    name: 'firstnames',
    displayKey: 'name',
    source: firstnames.ttAdapter()
  });

  // appending our newly creating div with all the element inside to #additionalnames
  $("#additionalnames").append(div);

  // incrementing count
  count++;
});

Also, I changed the took the liberty of removing the remover script all together. 另外,我改变了一起删除remover脚本的自由。 You can attach a click event to the button and look for the parent div and remove it using .closest() 您可以将click事件附加到按钮并查找父div并使用.closest()将其删除

Hope this helps. 希望这可以帮助。

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

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