0

我想使用 jQuery 使用“位置”div 的内容动态填充输入的数据源列表。我正在使用 Bootstrap typeahead,它运行良好,但我想让数据源列表动态化。

这是代码

<input
    data-path=".location"
    type="text"
    value=""
    id="location-filter"
    placeholder="Filter By Location ie. New York"
    data-control-type="textbox"
    data-control-name="desc-filter"
    data-control-action="filter"
    data-provide="typeahead"
    data-items="4" 
    data-source='["New York","Los Angeles","Chicago"]'
/>


<div class="block">
    <div class="type">Administration</div>
    <div class="desc">School Administrator</div>
    <div class="company">Administration Services LLC</div>
    <div class="location">New York</div>
    <div class="date">November 23</div>
</div><!--/block-->

<div class="block">
    <div class="type">Construction</div>
    <div class="desc">Roofing Contractor</div>
    <div class="company">Raise The Roof Inc.</div>
    <div class="location">Chicago</div>
    <div class="date">November 24</div>
</div><!--/block-->

<div class="block">
    <div class="type">Designer</div>
    <div class="desc">Web Designer</div>
    <div class="company">Web Designz Inc.</div>
    <div class="location">Los Angeles</div>
    <div class="date">November 25</div>
</div><!--/block-->
4

1 回答 1

0

您可以通过从具有以下内容的 div 中检索所有文本字段来做到这一点class="location"

$(function () {
    var category_array = $(".location").map(function() {
                         return $(this).text();
                     }).get();

    var autocomplete = $('#location-filter').typeahead({source: category_array}); 
});   

要从数组中删除重复项:

$(function () {
    var category_array = $(".location").map(function() {
                         return $(this).text();
                     }).get();

    // Remove duplicates
    // Note - this assumes the exact same string (including uppercase/lowercase) 
    category_array = $.grep(category_array, function(v, k){
                return $.inArray(v, category_array) === k;
          });

    var autocomplete = $('#location-filter').typeahead({source: category_array}); 
});  

请参阅此处获取小提琴

于 2012-12-04T22:19:48.260 回答