Html 自动完成获取输入值无效

Html autocomplete get input value not working

我正在为我的项目使用 twitters typeahead 插件。在用户使用以下代码从自动完成建议的列表中选择后,我试图获取输入元素的值

我的html:

<body>

    <input class="typeahead" type="text" placeholder="typeahead">
    <script
        src="https://code.jquery.com/jquery-3.2.1.js"
        integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
        crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.js"></script>

<script src="  https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js
             "></script>

我的JavaScript:

$(document).ready(function(){

  var array = ["one", "two", "three", "four", "five"]

  $(".typeahead").typeahead({source: array})


  $('.typeahead').bind('typeahead:select', function(ev, suggestion) {
    console.log('Selection: ' + suggestion);
  });
});

自动完成功能完美无缺。但是,问题是在用户从自动完成建议中做出选择后,我无法获得输入的值。这是插件的文档 https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md 谁能帮我解决问题?

根据documentation你需要使用:

afterSelect:

Call back function to execute after selected an item. It gets the current active item in parameter if any.

所以你的代码是:

$(".typeahead").typeahead({
    source: array,
    afterSelect: function (suggestion) {
        console.log('Selection: ' + suggestion);
    }
})

$(document).ready(function () {

    var array = ["one", "two", "three", "four", "five"]

    $(".typeahead").typeahead({
        source: array,
        afterSelect: function (suggestion) {
            console.log('Selection: ' + suggestion);
        }
    })
});
.box-sleeve li {
    display: inline-block;
    list-style-type: none;
    padding: 1em;
    background: red;
}

.box-sleeve {
    margin: 15px auto;
    padding: 0;
}

.showBorder {
    outline: 1px dashed #233354;
    outline-offset: 1px;
}

.box-tip {
    display: inline;
    margin: auto;
    position: relative;
    visibility: hidden;
    padding-left: 10px;
}

.numberCircle {
    border-radius: 90%;
    font-size: 12px;
    border: 2px solid #000;
    color: #fff;
    background: #000;
    padding: 0 4px;
}

.numberCircle span {
    text-align: center;
    display: block;
}

li.selected {
    color: #fff;
    background-color: #000;
}

@media (max-width: 768px) {
    .box-tip span {
        position: fixed;
        left: 10px;
    }

    .box-tip span.numberCircle {
        position: fixed;
        left: 236px;
    }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>


<input class="typeahead" type="text" placeholder="typeahead">