我了解如何在 vanilla js 中向数组中的所有元素添加事件监听器。但是当我使用knockout js时,只有数组中的最后一个元素受到影响。 我在js文件中做了一个函数
//when any of the li elements in the ul are clicked run this function
this.zoomOnLocation = function(){
//zooms in on the location you clicked
map.setZoom(18);
map.setCenter(marker.getPosition());
}
然后我有 ul 和 li 标签,单击时会触发该功能
<ul class="list" data-bind="foreach: locations">
<li data-bind="text: title, click: $parent.zoomOnLocation"></li>
</ul>
但是每当我单击该 li 时,我总是会获得位置数组中的最后一个位置。为什么会发生这种情况?如果您想查看我的项目,只需点击here
最佳答案
您需要将每个单独的位置传递给zoomOnLocation。像这样:
//when any of the elements in ul are clicked run this function
this.zoomOnLocation = function(data) {
//zooms in on the location you clicked
map.setZoom(18);
map.setCenter(data.location);
}
您获得最后一个位置的原因是您定义了一个标记(var 标记
),并在执行 for 循环时不断重新设置它。
关于javascript - 为什么我不能在使用 knockout js 时为数组中的每个元素添加事件监听器,而不仅仅是最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48130304/