$("ul li").show();
} else {
$("ul li").each( function() {
var pinyin = $(this).attr("pinyin"); var cityName = $(this).attr("cityName"); if (pinyin.indexOf(searchCityName) != -1
|| cityName.indexOf(searchCityName) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
}
}
$('#searchCityName').bind('input propertychange', function() {
searchCity();
}); </script></body></html>
注意点:
1、当我想实现在输入框内实时查询列表值,想到的第一种方案是用ajax,但是想了一下发现列表的值基本是固定的,为什么不一次加载出来呢,所以把后台代码改了一下,将所有城市详情加载出来。
2、输入框内值改变需要触发事件,我第一个想法是用onchange,但是事实上onchange是输入框值改变且输入框失去焦点,所以我最终用了keyup。keyup在电脑上测试都没有问题,但是在微信端,怎么都不生效。于是将keyup替换成了最终的 bind(‘input propertychange’, function() {} 。
3、在判断城市字符是否包含输入框内的字符时,我用contains函数,在火狐下测试没有任何问题,但是在chrome和微信客户端不生效。最后将contains替换成了indexOf。
例子二、使用jquery.autocomplete插件来实现。
1、使用设置
首页,要把插件的js代码嵌入到你自己的项目中去。
<script src="jquery.js" type="text/javascript"><!--mce:0--></script><script src="jquery.autocomplete.js" type="text/javascript"><!--mce:1--></script>2、使用方法
为要实现自动匹配提示的 input 表单添加 AutoComplete 功能。
<input id="query" name="q" />
初始化 AutoComplete 对象,确保正确加载 DOM 对象,否则IE下的用户可能会出现错误。
$('#query').autocomplete({ serviceUrl: 'service/autocomplete.ashx', // Page for processing autocomplete requests minChars: 2, // Minimum request length for triggering autocomplete delimiter: /(,|;)s*/, // Delimiter for separating requests (a character or regex) maxHeight: 400, // Maximum height of the suggestion list, in pixels width: 300, // List width zIndex: 9999, // List's z-index deferRequestBy: 0, // Request delay (milliseconds), if you prefer not to send lots of requests while the user is typing. I usually set the delay at 300 ms. params: { country: 'Yes'}, // Additional parameters onSelect: function(data, value){ }, // Callback function, triggered if one of the suggested options is selected, lookup: ['January', 'February', 'March'] // List of suggestions for local autocomplete });










