我使用javascript和knockoutjs使用viewmodel实现搜索过滤器。我无法使搜索过滤器工作。我是js文件
//Object Constructor Class for Locations
var Locations = function (title, lat, lng, id, marker){
this.title = title;
this.lat = lat;
this.lng = lng;
this.id = id;
this.marker = marker;
};
var viewModel = {
locations : [
new Locations('The Travel Cafe', 51.499542, -0.114134, '57540ed1498ef7771538048d'),
new Locations('Scooter Caffè', 51.50050110129609, -0.11393191896812872, '4ace5183f964a520d5cf20e3'),
new Locations('Four Corners', 51.50042544028603, -0.11365986202011345, '51e52b0b498e1d7ea31d88c1'),
new Locations('The Library Lounge at Marriott County Hall', 51.50193765161251, -0.12006535004714862, '543148b9498ec4159f277ce6'),
new Locations('Coleman Coffee Roasters', 51.500636, -0.112947, '57025a60498e2196f62e9548')
],
searchBox: ko.observable('')
};
viewModel.search = ko.computed(function() {
var self = this;
var searchResult = this.searchBox().toLowerCase();
return ko.utils.arrayFilter(self.locations, function(markerLocation) {
var title = markerLocation.title.toLowerCase();
var matched = title.indexOf(searchResult) > -1;
var marker = markerLocation.marker;
if (marker) {
marker.setVisible(matched);
}
//when I console.log(markerLocation.marker) i get undefined
return matched;
});
}, viewModel);
ko.applyBindings(viewModel);
这是html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="css/style.css">
<title>Neighbourhood Project</title>
</head>
<body>
<div class=".container">
<div id="map"></div>
</div>
<div>
<input type="text" placeholder="Search for locations" data-bind:"value: searchBox">
<ul data-bind="foreach: search">
<li data-bind="text: title "></li>
</ul>
</div>
</body>
<script type="text/javascript" src="scripts/knockout-3.4.2.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/map.js"></script>
<script async defer type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDRb_wXWOfFjBhfbUaH7NYcON4gSIa4wKo&v=3&callback=initMap"></script>
</body>
</html
我试图将viewmodel中的locations []数组声明为ko.observableArray()。但它没有用。可能有人弄清楚可能出现的问题。
答案 0 :(得分:1)
修复三个语法问题后,它对我有用:
</body>
代码。</html>
代替<html
data-bind="value: searchBox"
代替data-bind:"value: searchBox"
请参阅https://jsfiddle.net/twzn3jmu/6/。
然而,它是超级跛脚。
编辑:发现性能不佳的原因。 &#34;值&#34;是输入的错误绑定,使用&#34; textInput&#34;代替。