簡體   English   中英

如何從具有相同屬性的一堆元素中獲得具有“ aria-hidden”真值的元素?

[英]How do I get an element with `aria-hidden` true out of a bunch of elements that have the same attribute?

我試圖遍歷所有都將aria-hidden設置為false或true的元素列表,就我而言,只有一個元素將其設置為true,因此我需要知道當前可見的元素。

標記:

<div id="screen-1" class="setup-step-screen" aria-hidden="false"></div>
<div id="screen-2" class="setup-step-screen" aria-hidden="true"></div>
<div id="screen-3" class="setup-step-screen" aria-hidden="true"></div>

因此,我想檢索screen-1的ID:

var current_step = $('.setup-step-screen').each( function(i, obj) {
    if( $(obj).attr('aria-hidden') === 'false') {
        return $(obj).attr('id');
    }
});
console.log( current_step);

問題是,這返回:

a.fn.init(2) [div#screen-1.setup-step-screen, div#screen-2.setup-step-screen, selector: ".setup-step-screen", prevObject: n.fn.init(1), context: document]

這是因為我不知道何時停止each代碼,因此,這段代碼可以正常工作:

var current_step;
$('.setup-step-screen').each( function(i, obj) {
    if( $(obj).attr('aria-hidden') === 'false') {
        current_step = $(obj).attr('id');
    }
});

console.log(current_step);

但是我想在each任務中進行分配。

我該如何解決?

您可以使用簡單的querySelectorquerySelectorAll來實現此目的,無需庫也不需要任何循環:

 console.log( document.querySelector('[aria-hidden="false"]').id ); console.log( Array.from( document.querySelectorAll('[aria-hidden="true"]'), ({ id }) => id ) ); 
 <div id="screen-1" class="setup-step-screen" aria-hidden="false"></div> <div id="screen-2" class="setup-step-screen" aria-hidden="true"></div> <div id="screen-3" class="setup-step-screen" aria-hidden="true"></div> 

使用原始JavaScript

您可以在.querySelector方法內使用CSS選擇器。 就你而言

document.querySelectorAll('div[aria-hidden="false"]')

將返回所有將aria-hidden設置為false div元素。

這是代碼:

 const selection = document.querySelectorAll('div[aria-hidden="false"]') console.log(selection) 
 <div id="screen-1" class="setup-step-screen" aria-hidden="false"></div> <div id="screen-2" class="setup-step-screen" aria-hidden="true"></div> <div id="screen-3" class="setup-step-screen" aria-hidden="true"></div> 


使用jQuery

如果要使用jQuery,則可以使用相同的方法:

 var current_step; $('div[aria-hidden="false"]').each( function(i, obj) { current_step = $(obj).attr('id'); }); console.log(current_step); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="screen-1" class="setup-step-screen" aria-hidden="false"></div> <div id="screen-2" class="setup-step-screen" aria-hidden="true"></div> <div id="screen-3" class="setup-step-screen" aria-hidden="true"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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