怎么在js实现类似百度的自动补全功能
1个回答
展开全部
jquery ui 有一个autocomplete的插件,可以实现这个功能 在后台传一个 json格式的数组数据过来。JS如下:
$(function() {
var cache = {};
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 1,
source: function (request, response) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.ajax({
type: "POST",
url: mlog.variable.base+"/admin/post/autocomplete?keyword=" + extractLast( request.term ) ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
cache[ term ] = $.map(data, function(item){
return item.name
});
response( $.ui.autocomplete.filter(
$.map(data, function(item){
return item.name
}), extractLast( request.term ) ) );
},
error: function () {
alert("补全失败");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
$(function() {
var cache = {};
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 1,
source: function (request, response) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.ajax({
type: "POST",
url: mlog.variable.base+"/admin/post/autocomplete?keyword=" + extractLast( request.term ) ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
cache[ term ] = $.map(data, function(item){
return item.name
});
response( $.ui.autocomplete.filter(
$.map(data, function(item){
return item.name
}), extractLast( request.term ) ) );
},
error: function () {
alert("补全失败");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
AiPPT
2024-09-19 广告
2024-09-19 广告
随着AI技术的飞速发展,如今市面上涌现了许多实用易操作的AI生成工具1、简介:AiPPT: 这款AI工具智能理解用户输入的主题,提供“AI智能生成”和“导入本地大纲”的选项,生成的PPT内容丰富多样,可自由编辑和添加元素,图表类型包括柱状图...
点击进入详情页
本回答由AiPPT提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询