2015-11-03 51 views
1

我的html代碼:angularjs不集中下一個元素

<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

+0

工作在鉻文件:https://jsfiddle.net/Y2XLA/216/ –

+0

thanx的快速回復,我建立我的jsfiddle基於你提供的jsfiddle鏈接。但在我的情況下,我需要關注下一個元素,其他div –

回答

2

您的DOM遍歷計算策略是錯的怎麼能elem.next('')給你下一個輸入你需要先得到家長不是尋找輸入下一個DIV中

下一個()方法返回下一個同級元素所選元素的。 兄弟元素是共享相同父母的元素。

嘗試

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

+0

非常感謝你回答,我現在正在實施它。將在一段時間內接受它希望它的作品。 –

+0

對不起,我不能投票。我看着解決方案,但你可以告訴我如何找到這個語法,在console.log(elem)沒有這樣的父級obj。你能給我一些鏈接或解釋。我研究了3次迭代,所以我想知道它是如何工作的。 –

+0

我已經更新了我的答案,希望它能幫到 –