【问题标题】:jquery doesn't find particular element in ng-repeat [duplicate]jquery 在 ng-repeat 中找不到特定元素 [重复]
【发布时间】:2018-07-30 14:58:32
【问题描述】:

从下面的html代码开始

<div ng-repeat="item in list">
    <input type="text" class="texter">
</div>

我使用 jquery 来监听列出的任何输入的按键。

$('.texter').keypress(function(e){
    console.log(this);
}

但什么也没发生。即使有

$('input').keypress(function(e){
    console.log(this);
}

基本上,我想获取触发 keypress 事件的元素。

有没有办法用 jquery 来获取它?

请注意,我在提问之前已经搜索过答案,但似乎没有一个符合我的预期。

【问题讨论】:

  • 这就是为什么混合使用 jQuery 和 Angular 不是一个好主意的原因——每次 Angular 重绘 DOM 时,它都会破坏它不知道的 jQuery 事件绑定。而是在 Angular 中处理按键事件。
  • 尝试用$timeout 包裹它。它无法获取您的课程,因为它们尚未呈现。 jQuery 不是渲染摘要循环的一部分。 DOM 修改适用于指令,它们使用您可以尝试使用的 JQLite
  • 我强烈推荐 Angular 解决方案,但 $(document).on('keypress', '.texter', function(){console.log($(this))}) 会起作用跨度>
  • 那么如何用角度处理按键事件?

标签: jquery html angularjs


【解决方案1】:

为什么要使用 jQuery 来绑定事件监听器?您可以通过在 ng-repeat 中的输入中添加 ng-keypress 来使用 Angular 正确执行此操作

角度

HTML

<div ng-repeat="item in list">
  <input type="text" class="texter" ng-keypress="keypress($event)">
</div>

JS

angular
  .module("myApp", [])
  .controller('myController', ['$scope', function($scope) {

    $scope.list = [1,2,3];

    $scope.keypress = function(event){
      console.log(event);
    }
  }]);

DEMO

如果你坚持使用 jQuery 处理事件绑定,你应该使用$(document).on('keypress', ...)

$(document).on('keypress', '.texter', function(e){
  console.log(e);
});

【讨论】:

  • delegate 的使用已经被弃用了一段时间......
  • 更新了答案以使用on
  • 我不认为这应该被标记为重复的帖子。这是对链接帖子的部分回答,因为它与 Angular 相关,并且 jQuery 不应该用于绑定。也许将标题更改为具有更多上下文和相关性的内容“如何将按键事件绑定到 ng-repeat 中的输入”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2013-04-05
  • 2015-10-18
  • 1970-01-01
相关资源
最近更新 更多