第一版本:
1 2 3 4 5 6 7 8 9 22 23 24
25 94 95
第二版本(jquery、对象):
function Search(obj) { this.$search = $('#'+obj.inputId); this.$ul = this.init(this.$search); var array = ['task','text','text-area']; this.setData(array);} Search.prototype = { init: function(){ var that = this; this.$search.after('
'); // 绑定按钮 this.$search.keydown(function(e){ this.$choosed = $('.choosed'); // 按键 ↓ if(e.keyCode == 40){ e.preventDefault(); // 没有选择 if(this.$choosed.length == 0){ $('ul li:first').addClass('choosed'); } else if(this.$choosed[0] == $('ul li:last')[0]){ } else { this.$choosed.removeClass('choosed'); this.$choosed.next().addClass('choosed'); } } // 按键↑ if(e.keyCode == 38){ e.preventDefault(); if(this.$choosed.length == 0){ $('ul li:last').addClass('choosed'); } else if(this.$choosed[0] == $('ul li:first')[0]){ $('ul li:first').removeClass('choosed'); } else { this.$choosed.removeClass('choosed'); this.$choosed.prev().addClass('choosed'); } } // 按键回车 if(this.$choosed.length!=0 && e.keyCode == 13){ e.preventDefault(); // 所选内容 that.$search.val(this.$choosed.text()); // 移除ul下li that.$ul.find('li').remove(); } }) return $('input+ul'); }, setData: function(arr){ var that = this; that.$search.bind('input propertychange', function(){ // 获得输入内容 var value = $(this).val(); // 删除ul下所有li that.$ul.find('li').remove(); // 要添加的li var result = ''; $.each(arr, function(index, item) { if(value.length>0 && item.indexOf(value)==0){ result += '
'+value+''+item.substring(value.length)+''; } }); that.$ul.append(result); }); }, }