javascript - angularjs 不关注下一个元素

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

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

this is fiddle link of this code

最佳答案

你的 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

关于javascript - angularjs 不关注下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33493534/

相关文章:

javascript - 除非我提醒字符串,否则 RSS 计数不会出现

Javascript 将 2 个字段与 PHP while 循环内的第三个字段中的答案相乘

javascript - 创建横向滚动网站

javascript - 将一个字符串中的两个单独的正则表达式替换为括号

javascript - JQuery 无法尝试滚动到 "display: block"

javascript - 为禁用的元素停止事件冒泡

javascript - $.click() 和 $.trigger() 不会激活 Checkbox 的 onchange 函数

javascript - framework7 在加载时不显示选项卡 1

jquery - 不同维度的动态背景图片

javascript - Bootstrap 选择选择器 css 工作但 js 不工作