我对 knockout 还很陌生,所以我正在尝试弄清楚如何使我的小型应用程序正常工作。本质上,我希望 Google map 能够在点击时放大列表中的某个地点。谷歌地图部分正在工作。我创建了一个列表,并使用 knockout foreach 方法填写。然后,我将项目的值绑定(bind)到我的函数,但它不断抛出错误:
“knockout-3.4.2.js:1871 Uncaught ReferenceError:无法处理绑定(bind)“foreach:function(){returnplaces}” 消息:无法处理绑定(bind)“click: function (){return ZoomToPlace }” 消息:zoomToPlace 未定义”
这是我的这部分的 html:
<div class="scroll" id="myUL">
<ul data-bind="foreach: places">
<li>
<input data-bind="value: title, click: zoomToPlace" type="button" class="btn btn-small btn-link">
</li>
</ul>
</div>
这是我的js:
function PlacesList() {
var self = this;
self.places = ko.observableArray(locations);
self.title = ko.observable();
self.zoomToPlace = function() {
// Initialize the geocoder.
var geocoder = new google.maps.Geocoder();
// Get the place.
var address = this.title();
// Geocode the address/area entered to get the center. Then, center the map on it and zoom in
geocoder.geocode({
address: address,
componentRestrictions: {
locality: 'North York'
}
}, function(results, status) {
map.setCenter(results[0].geometry.location);
map.setZoom(15);
});
}
}
ko.applyBindings(new PlacesList(), document.getElementById("myUL"));
谢谢您,我们将不胜感激!
最佳答案
将 zoomToPlace
更改为 $parent.zoomToPlace
。
在 forEach
循环内,上下文是当前的 places
项。由于 zoomToPlace
不是 places
中的项目的方法,因此您收到了错误。
关于javascript - 通过knockout获取点击输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44611210/