繁体   English   中英

定位到具有tabindex属性的最后一个元素?

[英]Targetting the last element that has a tabindex attribute?

如何定位具有tabindex属性的给定父级的最后一个元素?

例如:

<div id="popup">
  <div id="some-element" tabindex="0">
  <div id="some-other-element" tabindex="0">
  <div id="yet-another-element" tabindex="0">
</div>

在这种情况下,它将定位到#yet-another-element

您可以将属性选择器[...]与jQuery .last()结合使用:

 let target = $('#popup [tabindex]').last(); console.log(target.attr('id')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="popup"> <div id="some-element" tabindex="0"> <div id="some-other-element" tabindex="0"> <div id="yet-another-element" tabindex="0"> </div> 


另一种方法是使用jQuery :last选择器:

$('#popup [tabindex]:last');

 let target = $('#popup [tabindex]:last'); console.log(target.attr('id')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="popup"> <div id="some-element" tabindex="0"> <div id="some-other-element" tabindex="0"> <div id="yet-another-element" tabindex="0"> </div> 


如果需要选择特定的tabindex值:

$('#popup [tabindex="0"]:last');

使用JavaScript:

结合使用带有Attribute selectors Document.querySelectorAll() ,以数组状对象的形式首先获取所有元素。 然后使用Spread syntax... )和array.length - 1从最后一个索引中获取元素:

 var div = document.querySelectorAll('#popup > div[tabindex="0"]'); var lastEl = [...div][div.length - 1]; console.log(lastEl.id) 
 <div id="popup"> <div id="some-element" tabindex="0"></div> <div id="some-other-element" tabindex="0"></div> <div id="yet-another-element" tabindex="0"></div> </div> 

使用jQuery:您可以将:last用作选择器的一部分:

 var lastEl = $('#popup > div[tabindex="0"]:last'); console.log($(lastEl).prop('id')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="popup"> <div id="some-element" tabindex="0"></div> <div id="some-other-element" tabindex="0"></div> <div id="yet-another-element" tabindex="0"></div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM