【问题标题】:Two ng-clicks on in same div在同一个 div 中单击两次
【发布时间】:2016-07-01 13:28:33
【问题描述】:

所以我一直在寻找答案,但我找不到答案。所以我所拥有的是特定 class="list-items" 中的项目的 ng-repeat。当我单击项目中的每个项目时,它应该执行一个功能。在每个列表中,我都有一个删除按钮,我想在单击时删除该项目。

所以一些代码供参考:

 <div ng-click="executeCallback($index)" class="list-items">
        <div class="item-info">
            <span>some info here</span>
        </div>
        <button ng-click="removeItem($index)">X</button>
 </div>

所以我现在就这样做了,在我的 CSS 中,我尝试使用按钮上的绝对位置和类似 10000 的 z-index 来显示它大于,但是当我单击 removeItem 按钮时,它仍然调用执行回调函数。我不希望它调用 executeCallback 函数。

有没有办法让 removeItem 函数仅在单击删除按钮而不是父类时调用?

【问题讨论】:

  • 这是因为当您单击按钮时,此单击事件会冒泡并触发父级上的单击处理程序。您需要在 removeItem() 内停止此事件的传播

标签: javascript html css angularjs


【解决方案1】:

您可以一键添加多个事件。

 <div ng-click="executeCallback($index)" class="list-items">
    <div class="item-info">
        <span>some info here</span>
    </div>
    <button ng-click="removeItem($index);$event.stopPropagation()">X</button>

【讨论】:

  • 非常感谢!
  • 我可能会将$event.stopPropagation() 移动到函数中,并让函数接受$event 并将其从前端传递到函数中以进行代码重用,但我不这样做不觉得 html 是这样的地方。
【解决方案2】:

ngClickngFocus 这样的指令在该表达式的范围内公开一个$event 对象。当 jQuery 存在时,该对象是 jQuery Event Object 的实例或类似的 jqLit​​e 对象。 Source

您可以直接在 HTML 模板中使用它,通过调用 $event.stopPropagation() 来停止其传播。只需将其添加到button 就可以了:

<button ng-click="removeItem($index);$event.stopPropagation()">X</button>

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 2013-09-18
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多