我正在使用脚本来自动填充搜索字段。我正在尝试添加“找不到结果”选项,当找不到任何后面的超链接时。我正在努力弄清楚如何添加一个else()来显示Text。
如何添加此脚本?谢谢。
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('data.json', function(data) {
$.each(data, function(key, value){
if (value.name.search(expression) != -1 || value.location.search(expression) != -1)
{
$('#result').append('<li class="list-group-item link-class"> '+value.name+'</li>');
}
});
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
答案 0 :(得分:0)
每次获得(显然)静态JSON值似乎很奇怪,因此我将其与其他一些内容一起缓存。请注意,如果结果数据不是静态的,您可能希望限制快速键人员的密钥。
看看要测试的实际JSON片段会有所帮助,但这应该可行。
let
来避免全局蔓延.remove()
,或许更快,使用最大实际数据进行测试a
添加到无结果,将其修复到正确的位置/ href
$(function() {
$.ajaxSetup({
cache: false
});
// cache selectors
let result = $('#result');
let state = $('#state');
let search = $('#search');
// create empty item
let resultItem = $('<li class="list-group-item link-class"></li>');
// create no results from empty item, COULD be dynamic `href` if needed
let noResultItem = resultItem.clone().html('<a href="#somewhere">No Results</a>');
// We might not need to get this every time? cache it
let dataHold = {}; // empty holder
$.getJSON('data.json', function(data) {
dataHold = data;
});
// change event also for paste etc users.
search.on('keyup change', function() {
// might be faster than .html(''). test this assumption
result.children().remove();
state.val('');// not sure what this is for or what sets it
let searchField = search.val();
let expression = new RegExp(searchField, "i");
// COULD cache the found results set IF it is large and append once
$.each(dataHold, function(key, value) {
if (value.name.search(expression) != -1 || value.location.search(expression) != -1) {
result.append(resultItem.clone().text(value.name));
}
});
// no match? use empty
if (!result.children().length) {
noResultItem.appendTo(result);
}
});
// do we want the class 'li.list-group-item' also?
result.on('click', 'li', function() {
let click_text = $(this).text().split('|');
search.val($.trim(click_text[0]));
result.children().remove();
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>Search: <input id="search" type="text" /></label>
<label>State: <input id="state" type="text" value="i do no know" /></label>
<ul id="result"></ul>
&#13;