Typeahead建议链接与jQuery单击不起作用

Typeahead建议链接与jQuery单击不起作用

本文介绍了Bootstrap Typeahead建议链接与jQuery单击不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从https://github.com/twitter/typeahead.js/下载的Bootstrap's typeahead苦苦挣扎3-4小时我正在尝试使用typeahead的建议添加单击功能,以使用javascript的window.location.href更改页面.我的typeahaed可与json值一起很好地工作

I'm struggling for 3-4 hours with Bootstrap's typeahead that I downloaded from https://github.com/twitter/typeahead.js/I'm trying to add a click function with typeahead's suggestion to change page with javascript's window.location.href.My typeahaed works well with json values

// 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结构;

In suggestion ul suggestions coming with 2 values; 1)Product Name, 2) Product Id. Sample html structure;

<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的重定向用户到产品详细信息页面上;

and I try to add click function to li's redirect user to product detail page with jquery code;

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

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

But it's always redirecting to: product-details.php?i=undefinedWhat is wrong with my code, what am I missing?

推荐答案

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:

You need to fetch the product Id it like this inside your click callback:

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

这篇关于Bootstrap Typeahead建议链接与jQuery单击不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 23:37