javascript - 为什么我不能在使用 knockout js 时为数组中的每个元素添加事件监听器,而不仅仅是最后一个元素

标签 javascript knockout.js

我了解如何在 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/

相关文章:

javascript - 为什么 `arr.find()` 返回 `undefined` ?

javascript - Bootstrap 选择错误 : Uncaught TypeError: Cannot read property '3'

javascript - 仅当从 Node 运行时,Rsync 才会失败,退出代码为 23

javascript - 将下拉列表中的值添加到 KnockoutJS 中另一个下拉列表中的任意一组值

javascript - 检查 knockout 绑定(bind)何时完成

javascript - knockout js foreach 绑定(bind)显示 [object object]

javascript - knockout : how to filter a foreach binding without using if

javascript - 使用函数生成器将值返回到 GraphQL Mutation 中的输出字段

javascript - 通过滚动到达导航栏区域时要剪切的元素

python - 在 Knockout attr 绑定(bind)下使用 Jinja2 模板