我的 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 变为空?
最佳答案
你的 dom 遍历方法是错误的 elem.next('')
怎么能给你下一个输入你需要先得到父而不是在下一个 div 中寻找输入
next() :方法返回所选元素的下一个兄弟元素。 兄弟元素是共享相同父元素的元素。
尝试
elem.bind('keydown', function (e) {
elem.parent('div').next().find('input').focus();
});
解释:
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/