我有一个搜索表单,用户可以在其中搜索产品。
搜索表单
<form class="navbar-form pull-right no_padding m_top_0 m_bottom_0 formSearchProduct" role="search" onsubmit="return false;" autocomplete="off">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="input-group p_xs_right_15 p_xs_left_15 p_sm_left_15 p_sm_right_15">
<input type="text" name="name" class="form-control m_xs_bottom_10 searchProduct" placeholder="Search Product" style="height: 24px; margin-top: 3px;">
<div class="showProds">
<ul class="searchedProducts" tabindex="0"></ul>
</div>
</div>
</form>
Controller for search:
public function searchProduct(Request $request)
{
$productName = $request->input('name');
$products = Product::where('name', 'LIKE', '%' . $productName . '%')->get();
return view('partials.search', compact('products'));
}
search.blade.php
@foreach($products as $product)
<li>
<a href="{{ url('/store/'.$product->code .'/'.Safeurl::make($product->name)) }}" class="link_scheme_color_main">
{{ $product->name }}
</a>
</li>
@endforeach
$('.searchProduct').keydown(function(e) {
var name = $(this).val();
var inputData = $('.formSearchProduct').serialize();
var prodList = $('.showProds');
var countList = prodList.find('ul li').length;
var prd = prodList.find('ul li');
if (name.length === 0) {
prodList.hide();
} else {
$.ajax({
url: '{{ url(' / store / product / search ') }}',
type: "POST",
data: inputData
}).done(function(m) {
//setTimeout(function() {
if (m) {
prodList.show();
prodList.find('ul.searchedProducts').html(m);
prodList.find('ul li').first().addClass('activeProduct');
} else {
prodList.hide();
}
//}, 500);
});
}
});
css .activeProduct {background: #ccc !important;}
问题是当用户按下/上箭头键时,类activeProduct
不能正常工作。它只停留在第一个列表项上。我遵循了这个教程,但是失败了。
在遵循教程之后,我有了这段代码,我尽了最大的努力:
$('.searchedProducts').keydown(function(e) {
var prodList = $('.showProds');
var countList = prodList.find('ul li').length;
var prd = prodList.find('ul li');
console.log(e.keyCode);
if (e.which === 40) {
var next = prd.removeClass('activeProduct').next('li');
next = next.length > 0 ? next : $('li:eq(0)');
next.addClass('activeProduct');
}
});
上面的函数根本没有被触发,我不知道为什么。
我想要的:
在搜索产品后,在下拉菜单中,用户应该能够使用上下方向键,当按下回车键时,用户应该能够进入产品页面。
非常感谢任何帮助。谢谢。
试试这个:
$('.searchedProducts').keydown(function(e) {
var prodList = $('.showProds');
var countList = prodList.find('ul li').length;
var prd = prodList.find('ul li');
// Note this line below
var active = prodList.find('ul li.activeProduct');
console.log(e.keyCode);
if (e.which === 40) {
// And this line
var next = active.removeClass('activeProduct').next('li');
next = next.length > 0 ? next : $('li:eq(0)');
next.addClass('activeProduct');
}
});
问题是您选择了所有列表项并删除了类activeProduct。下一个函数试图选择下一个列表项,但你有所有的选择,所以这是你的代码不工作(如果我是正确的)。通过选择活动产品,我认为您的代码将工作。
我已经解决了这个问题。
我使用了一个叫做selectize.js的jquery插件。
下面是我在我的Laravel应用程序中实现它的教程。