我希望能够找到某个类型的前一个元素,无论它是否包含在同一个父元素中。
在这种情况下,我想找到前面的 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>
关于javascript - 无论父级如何,查找相同类型的前一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30332497/