无法访问this.inputValue
函数中的showFilteredResult
。在showFilteredResult
内,this
的值应该是SearchFilter
对象对吗?如果我错了,请纠正我。
请在下面找到代码段。
var searchFilter=(function($){
function SearchFilter(){
this.inputValue=$("#searchInput").val().toUpperCase();
}
var filter=new SearchFilter();
SearchFilter.prototype.getResponse=function(){
var data=[{name:"Adele"},{name:"Agnes"},{name:"Billy"},{name:"Bob"},{name:"Calvin"},{name:"Christina"},{name:"Cindy"}];
this.showResult(data);
}
SearchFilter.prototype.showResult=function(data){
var markup=data.map(function(element){
return "<li><a href='#'>"+element.name+"</a></li>";
}).join("");
$("#result-container").empty();
$("#result-container").html(markup);
}
SearchFilter.prototype.showFilteredResult=function(){
var data=[{name:"Adele"},{name:"Agnes"},{name:"Billy"},{name:"Bob"},{name:"Calvin"},{name:"Christina"},{name:"Cindy"}];
var filteredData=data.filter(function(element){
var inputValue=this.inputValue; // error
var inputValue=$("#searchInput").val().toUpperCase();
var name=element.name.toUpperCase();
return inputValue.indexOf(name) >-1
});
console.log(filteredData);
this.showResult(filteredData);
}
function init(){
filter.getResponse();
$("#searchInput").on("keyup",function(e){
e.preventDefault();
filter.showFilteredResult();
});
}
return {init:init};
})(jQuery);
$(document).ready(function(){
searchFilter.init();
});
<input type="text" id="searchInput" placeholder="Search for names.." title="Type in a name">
<ul id="result-container">
</ul>