简体   繁体   English

使用JavaScript初始化BootStrap Typeahead时遇到问题

[英]Trouble Using JavaScript to Initialize BootStrap Typeahead

I have a simple Bootstrap typeahead that looks like this: 我有一个简单的Bootstrap typeahead,如下所示:

<input tabindex="1" type="text" name="q" class="search-query" id="wSearch" 
    data-provide="typeahead" data-items="3" 
    data-source='["AL", "AK", "AZ", "AR", "CA", "CO", "CT"]' 
    placeholder="Search">

That works just fine. 这很好用。

That said, I want the data to come from an ajax call so I want to convert the typeahead initialization with JavaScript. 也就是说,我希望数据来自ajax调用,所以我想用JavaScript转换typeahead初始化。 When I write this, my typeahead doesn't work: 当我写这篇文章时,我的预先输入不起作用:

var options = {
    items: 3,
    source: ["AL", "AK", "AZ", "AR", "CA", "CO", "CT"]
};
$("#wSearch").typeahead(options);

...

<input tabindex="1" type="text" name="q" class="search-query" 
    id="wSearch" placeholder="Search">

I can step through the code and see that it is being executed and I don't see any JavaScript errors, but the typeahead simply doesn't work. 我可以单步执行代码并看到它正在执行,我没有看到任何JavaScript错误,但是typeahead根本不起作用。

I've gotta be missing something trivial but, after staring at this for quite a while, I'm still not seeing it. 我不得不遗漏一些微不足道的东西,但是在盯着它看了很长一段时间之后,我仍然没有看到它。

Any thoughts? 有什么想法吗?

Surround your code with $(document).ready(); $(document).ready();包围代码$(document).ready(); its attempting to load before the DOM is ready. 它试图在DOM准备好之前加载。

$(document).ready(function(){
   var options = {
    items: 3,
    source: ["AL", "AK", "AZ", "AR", "CA", "CO", "CT"]
   };
   $("#wSearch").typeahead(options);
});

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

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