[英]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.