angularjs没有关注下一个元素

时间:2015-11-03 07:25:11

标签: javascript jquery html css angularjs

我的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:单击enter按钮时,此代码不会关注下一个元素。表明 nextElementSibling:null和nextSibling:console.log(elem)上的文本 2:但是当我在表单标签中删除标签标签和div时,它会开始工作,因为它专注于下一个元素。

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

this is fiddle link of this code

1 个答案:

答案 0 :(得分:2)

你的dom遍历approch错误怎么能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