Bootstrap 预先输入建议链接 jquery 点击无效

Bootstrap typeahead suggestion links with jquery click not working

我用从 https://github.com/twitter/typeahead.js/ 下载的 Bootstrap's typeahead 苦苦挣扎了 3-4 个小时 我正在尝试根据 typeahead 的建议添加点击功能,以使用 javascript 的 window.location.href 更改页面。 我的 typeahaed 与 json 值

配合得很好
// Typeahead
$("#search-product").typeahead({
    ajax: {
        url: "_inc/search-json.php?product=",
        timeout: 500,
        displayField: "product_name",
        triggerLength: 3,
        method: "get",
        preDispatch: function (query) {
            return {
                search: query
            }
        },
    }
});

在建议中 ul 有 2 个值的建议; 1) 产品名称,2) 产品编号。示例 html 结构;

<ul class="typeahead dropdown-menu">
    <li data-value="166" class=""><a href="#"><strong>TK03</strong>0</a></li>
    <li data-value="167"><a href="#"><strong>TK03</strong>1</a></li>
</ul>

并且我尝试使用 jquery 代码将点击功能添加到 li 将用户重定向到产品详细信息页面;

var productId = $('.typeahead li').data("value");
$(".typeahead").on( "click", "li", function() {
    window.location.href = "/product-details.php?i=" + productId;
});

但它总是重定向到:product-details.php?i=undefined 我的代码有什么问题,我错过了什么?

var productId = $('.typeahead li').data("value"); // Doesnt make any sense outside the click callback. Instead write it within the callback like shown below.

您需要在 click 回调中像这样获取产品 ID:

$(".typeahead").on( "click", "li", function() {
   var productId = $(this).data("value");  // $(this) refers to the clicked li
   window.location.href = "/product-details.php?i=" + productId;
});