[英]Find previous element of same type regardless of parent
我希望能够找到某个类型的前一个元素,无论它是否包含在同一个父元素中。
在这种情况下,我想找到以前的input[type="text"]
元素并给它焦点。
目前我可以选择同一父节点中的前一个兄弟节点,但希望能够将其过滤为仅input[type="text"]
元素并允许前一个父节点。
接受的答案只是vanilla javascript。
document.addEventListener('keydown', function(e) { // if backspace is pressed and the input is empty if (e.keyCode === 8 && e.target.value.length === 0) { // This should give focus to the previous input element e.target.previousSibling.previousSibling.focus(); } }, false);
<div> <input type="text"> <input type="text"> </div> <div> <input type="text"> <input type="text"> </div> <div> <input type="text"> <input type="text"> </div>
您可以使用querySelectorAll
获取所有匹配的元素,然后循环查找您所在的元素,然后将焦点放在上一个元素上。 querySelectorAll
的结果是“文档顺序”。
document.addEventListener('keydown', function(e) { if (e.keyCode === 8 && e.target.value.length === 0) { // This should give focus to the previous input element var inputs = document.querySelectorAll('input[type="text"]'); for(var i = 1; i < inputs.length; i++){ if(inputs[i] == e.target){ inputs[i-1].focus(); break; } } } }, false);
<div> <input type="text"> <input type="text"> </div> <div> <input type="text"> <input type="text"> </div> <div> <input type="text"> <input type="text"> </div>
您可以使用以下方法,而不是侦听文档上发生的所有事件,查找在某些元素上触发的事件。
选择并缓存包含要循环的元素的范围元素。
从我们之前在列表中选择的范围中选择并缓存您要循环的所有元素。
在循环的每次迭代中循环遍历列表中的所有元素:
使用此方法:
var scope = document.querySelector('.scope'); var inputs = scope.querySelectorAll('input[type="text"]'); for (var i in Object.keys(inputs)) (function(index){ inputs[i].addEventListener('keydown', function(e){ if (e.which === 8 && this.value.length === 0) { var next = index - 1; if (next < 0) next = inputs.length - 1; inputs[next].focus(); } }, false); })(i);
<div class="scope"> <div><input type="text"><input type="text"></div> <div><input type="text"><input type="text"></div> <div><input type="text"><input type="text"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.