twitter.typeahead.js не работает в проекте mvc ядра asp.net

Я работаю над проектом asp.net mvc, который будет показывать соответствующие результаты поиска, набирая их под полем поиска. Я добавил в проект twitter.typeahead.js с менеджером пакетов bower. Вот мой код

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>  
    <script src="~/lib/typeahead.js/dist/typeahead.bundle.js"></script>
    <title></title>
</head>
<body>
    <div id="bloodhound">
        <input class="typeahead" type="text" placeholder="States of USA">
    </div>

</body>
</html>

<script type="text/javascript">

    $(document).ready(function () {
        var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
            'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
            'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
            'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
            'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
            'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
            'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
            'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
            'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
        ];

        var states = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.whitespace,
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            // `states` is an array of state names defined in "The Basics"
            local: states
        });

        $('#bloodhound .typeahead').typeahead({
            hint: true,
            highlight: true,
            minLength: 1
        },
            {
                name: 'states',
                source: states
            });
    });
</script>

Теперь выдает эту ошибку

Использование getPreventDefault () не рекомендуется. Вместо этого используйте defaultPrevented. TypeError: $ (...). Typeahead не является функцией. jQuery.Deferred исключение: $ (...). typeahead не является функцией @ http://localhost:54331/Home/Search:85:9 j @ https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js:2:29997 g / https: // ajax. googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js:2:30313 undefined

bower.json

{
  "name": "typeahead.js",
  "version": "0.11.1",
  "main": "dist/typeahead.bundle.js",
  "dependencies": {
    "jquery": ">=1.7"
  },
  "devDependencies": {
    "jquery": "~1.7",
    "jasmine-ajax": "~1.3.1",
    "jasmine-jquery": "~1.5.2"
  },
  "homepage": "https://github.com/twitter/typeahead.js",
  "_release": "0.11.1",
  "_resolution": {
    "type": "version",
    "tag": "v0.11.1",
    "commit": "87de059a7820b1e223f1c704fa12a624dbce3a4f"
  },
  "_source": "https://github.com/twitter/typeahead.js.git",
  "_target": "v0.11.1",
  "_originalSource": "typeahead.js",
  "_direct": true
}

person Mohit K. Bhowmik    schedule 31.07.2017    source источник
comment
попробуйте jQuery версии 1.10 для проверки появления ошибки?   -  person Code Spy    schedule 31.07.2017
comment
Он говорит, что jQuery не определен, а также $ не определен после попытки этого!   -  person Mohit K. Bhowmik    schedule 31.07.2017
comment
@ MohitK.Bhowmik, какой src вы пробовали для jquery 1.1?   -  person MJK    schedule 31.07.2017
comment
вы уверены, что typeahead.bundle.js не возвращает ошибку 404? проверьте, правильно ли он загружен   -  person Spring    schedule 31.07.2017
comment
1) Поделиться снимком экрана. 2) Проверьте, включен ли только один плагин jQuery на странице 3) Добавьте jQuery над плагином typeScript 4) Убедитесь, что машинописный текст, вызываемый в документе, готов   -  person Code Spy    schedule 31.07.2017
comment
@MJK ‹скрипт src = code.jquery.com/jquery-1.10.0.js целостность = sha256-iqD4S1Mx78w8tyx9UEwrxuvYYdoAPXLDPfmc5lDUUx0 = crossorigin = анонимный ›‹/script›   -  person Mohit K. Bhowmik    schedule 31.07.2017
comment
@ MohitK.Bhowmik попробуй это <script src="http://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>   -  person MJK    schedule 31.07.2017
comment
@ jolly.exe У Mohit K недостаточно репутации, чтобы поделиться снимком экрана   -  person MJK    schedule 31.07.2017
comment
@bRIMOs не возвращает ошибку 404!   -  person Mohit K. Bhowmik    schedule 31.07.2017
comment
@ jolly.exe включен только один плагин jQuery; я добавил jQuery над плагином машинописного текста; да, машинопись вызывается в готовом документе!   -  person Mohit K. Bhowmik    schedule 31.07.2017
comment
@ MohitK.Bhowmik, скажите, пожалуйста, какую версию typeahead вы используете?   -  person Code Spy    schedule 31.07.2017


Ответы (2)


Давайте получим это поработать: P

ДЕМО: https://jsfiddle.net/ipsjolly/6ydvth9q/1/

TypeAhead версии 1.1.1 URL: https://cdnjs.cloudflare.com/ajax/libs/corejs-typeahead/1.1.1/typeahead.jquery.min.js

jQuery последняя версия

Источник: http://twitter.github.io/typeahead.js/examples/

Код TypeScript не содержит Bloodhound, я не знаю, зачем он нужен: D

HTML

<div id="the-basics">
  <input class="typeahead" type="text" placeholder="States of USA">
</div>

JS

<script type="text/javascript">
    var substringMatcher = function(strs) {
        return function findMatches(q, cb) {
            var matches, substringRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(strs, function(i, str) {
                if (substrRegex.test(str)) {
                    matches.push(str);
                }
            });

            cb(matches);
        };
    };

    var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
        'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
        'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
        'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
        'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
        'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
        'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
        'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
        'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
    ];

    $('#the-basics .typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    }, {
        name: 'states',
        source: substringMatcher(states)
    });
</script>
person Code Spy    schedule 31.07.2017

Чтобы уточнить, проблема не в Бладхаунде.

Bloodhoud - это механизм предложений typeahead.js

В этот ответ о переполнении стека добавлен jsfiddle, который отлично работает с ищейкой.

Я также создал один jsfiddle с обновленной версией typhead bloodhound и версией jquery.

JQuery: 3.2.1 Typehead: 1.1.1

Вы можете попробовать эту версию для своего проекта

const suggestions = [{
    value: 'bloodhound1'
}, {
    value: 'bloodhound2'
}, {
    value: 'bloodhound3'
}, {
    value: 'typeahead1'
}, {
    value: 'typeahead2'
}]

var bloodhoundSuggestions = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    sufficient: 3,
    local: suggestions
});

const $tagsInput = $('#tagsInput')
$tagsInput.typeahead({
    hint: true,
    highlight: true,
    minLength: 1
}, {
    name: 'suggestions',
    displayKey: 'value',
    source: bloodhoundSuggestions
});
person MJK    schedule 31.07.2017