【问题标题】:Bootstrap typeahead not working in MVC 5Bootstrap 预输入在 MVC 5 中不起作用
【发布时间】:2014-05-30 10:08:01
【问题描述】:

在我的 mvc 项目中,我试图实现自动完成但它不起作用(打字机)我做的一切都是正确的,但无法得到它。下面是我的代码。谁能帮忙

<script type="text/javascript">
$(document).ready(function () {

    $("#Search").typeahead({
        source: function (query, process) {
            var countries = [];
            map = {};

            // This is going to make an HTTP post request to the controller
            return $.post('/Registration/GetPossibleLocations', { query: query }, function (data) {

                // Loop through and push to the array
                $.each(data, function (i, country) {
                    map[country.Name] = country;
                    countries.push(country.Name);
                });

                // Process the details
                process(countries);
            });
        },
        updater: function (item) {
            var selectedShortCode = map[item].ShortCode;

            // Set the text to our selected id
            $("#details").text("Selected : " + selectedShortCode);
            return item;
        }
    });

});

<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript">     </script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js" type="text/javascript"></script>

<div>
    <input type="text" id="Search" data-provide="typeahead" placeholder="Country" autocomplete="off" />    
        </div>

【问题讨论】:

  • 你能指定什么不工作是什么意思吗?您收到 ajax 调用的响应了吗?您的 countries 变量中是否有任何元素?
  • 甚至没有预先输入调用控制器它卡住什么也没发生没有错误没有数据
  • typeahed.js Github site 上有一条通知:注意:bloodhound.js 和 typeahead.jquery.js 都依赖于 jQuery 1.9+。您使用的是 1.8.3。也许这就是问题所在。
  • 即使更改为 1.10 也无法正常工作

标签: javascript jquery asp.net-mvc twitter-bootstrap-3 bootstrap-typeahead


【解决方案1】:

typeahead() 至少等待两个参数。第一个参数是一个选项数组,然后您可以定义多个数据集。 source 必须在数据集中定义。

查看用法:https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#usage

正如文档所述,source 必须计算建议集(即 JavaScript 对象数组)以进行查询。您正在传递一个字符串数组。 除此之外,您还必须设置displayKey

如果您在文本字段中写入内容,source 将首次执行。

我为你做了一个小提琴:http://jsfiddle.net/dtengeri/EhJvB/

您的代码应如下所示:

<script type="text/javascript">
$(document).ready(function () {
  // Notice the first empty object. You can specify options in it.
  $("#Search").typeahead({}, {
      displayKey: 'Name',
      source: function (query, process) {
          var countries = [];
          map = {};

          // This is going to make an HTTP post request to the controller
          return $.post('/Registration/GetPossibleLocations', { query: query }, function (data) {

              // Loop through and push to the array
              $.each(data, function (i, country) {
                  map[country.Name] = country;
                  // You have to create an array of JS objects. 
                  // Typeahead will use the displayKey to fetch data from the object.
                  countries.push({'Name': country.Name});
              });

              // Process the details
              process(countries);
          });
      },
      ...        
  });

});

【讨论】:

  • 当我在 map = {} 下方保持警报时,警报没有触发我检查了 js 错误,但它什么也没显示
  • 我已经更新了帖子。您必须先在文本字段中输入一些内容,才能触发 source 回调。
【解决方案2】:

我更喜欢使用 Bloodhound 集成来获取我的数据源。这是我如何使用它的示例:

捆绑包:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/layoutScriptsBundle").Include(
            "~/_js/_lib/jquery/jquery-{version}.js",
            "~/_js/_lib/bootstrap/bootstrap.js",
            "~/_js/_lib/typeahead.js/typeahead.bundle.js",
            "~/_js/_lib/handlebars.js/handlebars-v1.3.0.js"));

        bundles.Add(new StyleBundle("~/bundles/css/libs/layoutStylesBundle").Include(
            "~/_css/_lib/bootstrap/bootstrap.css",
            "~/_css/_lib/typeahead.js/typeahead.js-bootstrap.css"));
    }
}

JavaScript:

<script>
    window.siteNS = window.siteNS || {};
    jQuery(document).ready(function ($) {
        siteNS.typeaheadRemoteUrl = '@Url.ActionFor((ExampleController c) => c.GetTypeaheadData(null))?q=%QUERY';

        var myTypeaheadData = new Bloodhound({
            datumTokenizer: function (d) {
                return Bloodhound.tokenizers.whitespace(d.value);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: siteNS.typeaheadRemoteUrl,
                rateLimitWait: 250,
                ajax: { cache: false }
            }
        });

        myTypeaheadData.initialize();

        $('#myTypeahead').typeahead({
            autoselect: true,
            highlight: true,
            hint: true,
            minLength: 1
        }, {
            source: myTypeaheadData.ttAdapter(),
            name: 'myTypeaheadDatasetName',
            displayKey: 'ItemName',
            templates: {
                empty: '',
                footer: '',
                header: '',
                suggestion: Handlebars.compile('<p>{{ItemName}} - {{ItemID}}</p>')
            }
        });
    });
</script>

HTML:

<div class="form-group">
    <label class="control-label col-lg-4">Search/Autocomplete</label>
    <div class="col-lg-8 myTypeaheadContainer">
        <input id="myTypeahead" type="text" class="form-control">
        <span class="help-block">Using typeahead.js</span>
    </div>
</div>

【讨论】:

    【解决方案3】:

    试试这个

    please remove autocomplete="off" from tag  
    
    
        <div>
        <input type="text" id="Search" data-provide="typeahead" placeholder="Country" />    
        </div>
    

    【讨论】:

    • 不起作用问题是当我在 map={} 下方保持警报时,我不知道 post call 是否正在触发,它什么也没显示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    相关资源
    最近更新 更多