簡體   English   中英

無論父級如何,查找相同類型的上一個元素

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

您可以使用以下方法,而不是偵聽文檔上發生的所有事件,查找在某些元素上觸發的事件。

選擇並緩存包含要循環的元素的范圍元素。

從我們之前在列表中選擇的范圍中選擇並緩存您要循環的所有元素。

在循環的每次迭代中循環遍歷列表中的所有元素:

  1. 使用立即調用的函數表達式(IIFE)創建一個新的詞法范圍,您可以在其中存儲與該范圍中的當前元素關聯的索引。
  2. 將事件偵聽器分配給該元素的'keydown'事件,在該事件中檢查是否按下了退格鍵並且字段為空; 如果這些檢查通過:
    • 將焦點設置在先前選擇的元素列表中的前一個元素上;
    • 或者,如果當前元素是列表中的第一個元素,則將焦點設置在列表中的最后一個元素上。

使用此方法:

  • 你只查詢DOM兩次(在有限的范圍內),
  • 您沒有收聽對整個文檔中的每個元素觸發的每個keydown事件,以及
  • 你可以通過從開始到結束的循環無限循環。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM