2016-01-29 95 views
1

我無法獲得在此處找到的默認Twitter typeahead自定義模板工作:http://twitter.github.io/typeahead.js/examples/#custom-templates 我能夠使默認演示工作得很好。 這裏是我的js代碼Twiiter Typeahead自定義模板 - 獲取默認示例工作

jQuery(document).ready(function() { 

var bestPictures = [ 
    {"year": "1996", "value": "Tom", "url": "http://example.com"}, 
    {"year": "1998", "value": "Tim", "url": "http://example.com"} 
]; 


$('#custom-templates .typeahead').typeahead(null, { 
    name: 'best-pictures', 
    display: 'value', 
    source: bestPictures, 
    templates: { 
    empty: [ 
     '<div class="empty-message">', 
     'unable to find any Best Picture winners that match the current query', 
     '</div>' 
    ].join('\n'), 
    suggestion: Handlebars.compile('<div><strong>{{value}}</strong> – {{year}}</div>') 
    } 
    }); 
}); 

我找不到例子在他們從bestPictures的源代碼。我也有安裝把手。當我在信t在搜索框中鍵入,我的控制檯日誌顯示typeahead.bundle.js在這條線this.source is not a functionthis.source(query, sync, async);

此外,我願做一個重定向一次下拉選項被選中,類似

on('typeahead:selected', function(event, datum) { 
    window.location = datum.url 
}); 
+0

'js'的哪個部分沒有返回預期的結果? – guest271314

+0

那麼,下拉沒有被填充。我正在接收typeahead.js內部的錯誤 –

+0

嘗試使用'Bloodhound',將'bestPicture'作爲對象傳遞給'suggestion'函數,請參閱文章 – guest271314

回答

0

嘗試使用Bloodhound,在.typeaheadsuggestions函數返回對象bestPictures作爲訪問的屬性

jQuery(document).ready(function() { 
 

 
    var bestPictures = [{ 
 
    "year": "1996", 
 
    "value": "Tom", 
 
    "url": "http://example.com" 
 
    }, { 
 
    "year": "1998", 
 
    "value": "Tim", 
 
    "url": "http://example.com" 
 
    }]; 
 

 
    var pictures = new Bloodhound({ 
 
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"), 
 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
 
    local: $.map(bestPictures, function(d) { 
 
     return { 
 
     value: d.value, 
 
     // pass `bestPictures` to `suggestion` 
 
     suggest: d 
 
     } 
 
    }) 
 
    }); 
 

 
    pictures.initialize(); 
 

 
    $("#custom-templates .typeahead").typeahead(null, { 
 
    name: "best-pictures", 
 
    display: "value", 
 
    source: pictures.ttAdapter(), 
 
    templates: { 
 
     notFound: [ 
 
     "<div class=empty-message>", 
 
     "unable to find any Best Picture winners that match the current query", 
 
     "</div>" 
 
     ].join("\n"), 
 
     suggestion: function(data) { 
 
     // `data` : `suggest` property of object passed at `Bloodhound` 
 
     return "<div><strong>" + data.suggest.value + "</strong>" 
 
       + data.suggest.year + "</div>" 
 
     } 
 
    } 
 
    }); 
 
});
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> 
 
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"> 
 
</script> 
 

 
<div id="custom-templates"> 
 
    <input type="text" class="typeahead" placeholder="Best picture winners" /> 
 
</div>

+0

謝謝!完美的作品! –

相關問題