【问题标题】:angularjs not focussing on next elementangularjs不关注下一个元素
【发布时间】:2015-11-03 17:15:33
【问题描述】:

我的html代码:

<div ng-app="app">
<form>
    <div class="form-group">
      <label >Username</label>
      <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/>  
      </div>
     <div class="form-group">
      <label >Password</label>         
       <input focus type="password" class="form-control" id="loginPwd" ng-model="userForm.password"  required/>
     </div>
</form>

我的js代码:

var app = angular.module('app', []); app.directive('focus', function () {
return {
    restrict: 'A',
    link: function ($scope, elem, attrs) {

        elem.bind('keydown', function(e) {
        var code = e.keyCode || e.which;
        if (code === 13) {
          console.log(elem);
          elem.next()[0].focus();
          //e.preventDefault();
          //elem.next().focus();
        }
      });
    }
}
})

1:当点击输入按钮时,此代码不关注下一个元素。表明 nextElementSibling: null 和 nextSibling: console.log(elem) 上的文本 2:但是当我删除表单标签中的标签标签和div时,它开始工作,因为它专注于下一个元素。

所以,问题是如何在不删除 div 和标签的情况下使其工作。为什么 nextElementSibling 会为空?

this is fiddle link of this code

【问题讨论】:

  • chrome 中的工作文件:jsfiddle.net/Y2XLA/216
  • 感谢您的快速回复,我根据您给出的 jsfiddle 链接构建了我的 jsfiddle。但就我而言,我需要关注其他 div 之后的下一个元素

标签: javascript jquery html css angularjs


【解决方案1】:

你的 dom 遍历方法是错误的,elem.next('') 如何给你下一个输入,你需要先获取父级而不是在下一个 div 中查找输入

next() : 方法返回被选元素的下一个兄弟元素。 兄弟元素是共享相同父元素的元素。

试试

elem.bind('keydown', function (e) {
                 elem.parent('div').next().find('input').focus();
            });

Working Fiddle

解释:

   elem.bind('keydown', function(e) {
               var code = e.keyCode || e.which;
               if (code === 13) {

                   console.log(elem); // "elem" is the current element which have focus you can see it in console it's always point to the current element .
                   elem.parent('div').next().find('input')[0].focus(); //Explained as following 

                 `elem.parent('div')`
                   to find parent div now we are on div which have
                   current element now `.next()`
                   to move to next div(next sibling element) and than find input inside it by `find('input')`
                   to make focus over it </b>

                   console.log(elem.parent('div')); //parent Div obj

               }

在这里查看angularjs-dom-selector

【讨论】:

  • 非常感谢您的回答,我现在正在实施它。将标记它在一段时间内被接受,希望它的作品。
  • 对不起,我不能投票。我研究了解决方案,但你能告诉我你如何找到这个语法,在 console.log(elem) 上没有这样的父 obj。你能给我一些链接或解释吗?我研究了 3 次迭代,所以我想知道它是如何工作的。
  • @deepaksinghpawar 仍然对它的工作感到困惑?
  • 我理解并且它的工作无缝感谢您的解释。
猜你喜欢
  • 2018-06-27
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
相关资源
最近更新 更多