这二天开始用jquery.autocomplete这个自动完成插件。功能基本比较强大,但自己在实际需求中发现还是有一处不足!
问题是这样:当我定义了一个本地数据JS文件时,格式为JSON式的数组。如下:
var
stockInfoJson
=
[
{ name:
"
深发展A
"
, code:
"
000001
"
,spell:
"
sfza
"
},
{ name:
"
万科A
"
, code:
"
000002
"
,spell:
"
wka
"
},
{ name:
"
ST 国 农
"
, code:
"
000004
"
,spell:
"
stgn
"
},
{ name:
"
世纪星源
"
, code:
"
000005
"
,spell:
"
sjxy
"
},
{ name:
"
深振业A
"
, code:
"
000006
"
,spell:
"
szya
"
},
{ name:
"
ST 达 声
"
, code:
"
000007
"
,spell:
"
stds
"
},
{ name:
"
ST宝利来
"
, code:
"
000008
"
,spell:
"
stbll
"
},
{ name:
"
中国宝安
"
, code:
"
000009
"
,spell:
"
zgba
"
},
{ name:
"
S ST华新
"
, code:
"
000010
"
,spell:
"
ssthx
"
},
{ name:
"
山航B
"
, code:
"
200152
"
,spell:
"
shb
"
},
{ name:
"
*ST帝贤B
"
, code:
"
200160
"
,spell:
"
stdxb
"
},
{ name:
"
雷伊B
"
, code:
"
200168
"
,spell:
"
lyb
"
},
{ name:
"
宝石B
"
, code:
"
200413
"
,spell:
"
bsb
"
},
{ name:
"
小天鹅B
"
, code:
"
200418
"
,spell:
"
xteb
"
},
{ name:
"
粤高速B
"
, code:
"
200429
"
,spell:
"
agsb
"
},
{ name:
"
宁通信B
"
, code:
"
200468
"
,spell:
"
ltxb
"
},
{ name:
"
晨鸣B
"
, code:
"
200488
"
,spell:
"
cmb
"
},
{ name:
"
珠江B
"
, code:
"
200505
"
,spell:
"
zjb
"
},
{ name:
"
闽灿坤B
"
, code:
"
200512
"
,spell:
"
mskb
"
},
{ name:
"
华电国际
"
, code:
"
600027
"
,spell:
"
hdgj
"
}
];
现在希望用户输入的内容在code及spell属性中进行匹配。但默认的jquery.autocomplete.js插件,当用户输入内容时总是去匹配name.
通过查看源码没有发现有对此需求进行支持的相关属性,这点倒不方便了!所以决定对jquery.autocomplete.js进行修改,使其支持自定义的匹配模式。
首先在429行添加一个事件
reasultSearch:
null
,
//
add by fengyan 添加一个自定义查询结果的事件属性
在$.Autocompleter.Cache中添加一个缓存数据变量450行
var
allData
=
new
Array();
//
add by fengyan 数组变量 缓存所有数据
在populate()方法中添加511行添加
allData.push(row);
//
add by fengyan 将每行数据存放刚才定义的数组变量中
然后再在load: function(q)方法中568行添加一个判断
//
add by fengyan 调用用户自定义查询方法
else
if
(
typeof
(options.reasultSearch)
==
"
function
"
)
{
var
csub
=
[];
$.each(allData,
function
(i, row) {
var
ms
=
options.reasultSearch(row,q);
if
(ms
!=
null
&&
ms
!=
false
)
{
csub.push(ms);
}
});
return
csub;
}
然后前台调用的时候可以使用resultSearch属性进行扩展我们自己想要的查询方式
$(
function
(){
$(
"
#suggest1
"
).autocomplete(stockInfoJson, {
minChars:
1
,
matchCase:
false
,
//
不区分大小写
autoFill:
false
,
max:
10
,
formatItem:
function
(row, i, max,term) {
var
v
=
$(
"
#suggest1
"
).val();
return
row.name
+
"
(
"
+
row.code
+
"
)
"
;
if
(row.code.indexOf(v)
==
0
||
row.spell.indexOf(v)
==
0
)
{
return
row.name
+
"
(
"
+
row.code
+
"
)
"
;
}
else
return
false
;
},
formatMatch:
function
(row, i, max) {
return
row.name
+
"
(
"
+
row.code
+
"
)
"
;
},
formatResult:
function
(row) {
return
row.code;
},
reasultSearch:
function
(row,v)
//
本场数据自定义查询语法 注意这是我自己新加的事件
{
//
自定义在code或spell中匹配
if
(row.data.code.indexOf(v)
==
0
||
row.data.spell.indexOf(v)
==
0
)
{
return
row;
}
else
return
false
;
}
});
});