簡體   English   中英

Bootstrap Typeahead建議鏈接與jQuery單擊不起作用

[英]Bootstrap typeahead suggestion links with jquery click not working

我在從https://github.com/twitter/typeahead.js/下載的Bootstrap's typeahead上苦苦掙扎了3-4小時,我正嘗試添加一個帶有typeahead建議的click函數,以使用javascript的window.location.href更改頁面。 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)產品ID。 樣本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;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM