简体   繁体   中英

How to check if the last element inside another element is focused

Is there any jQuery code for finding the last <a> tag inside a <div> is focussed using keyboard. IE if the last <a> tag inside a <div> is focussed, a Javascript function has to be triggered

<div>
  <a>1</a>
  <a>2</a>
  <a>3</a>
  <!-- -->
  <!-- -->
  <a>n</a>
<div>

just select the last a element and add focus eventlistener with JQuery

 $("div a:last-child").focus(function(e){ console.log("last <a> focused"); e.preventDefault(); //prevent infinite loop }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <a href="#">a tag</a> <a href="#">a tag</a> <a href="#">a tag</a> <a href="#">a tag</a> <a href="#">a tag</a> </div> 

Use :last-child selector to find the last element into <div> (in this case the last anchor <a> ) and use also .focus(<callback>) to listen on focus event over any element:

$('div a:last-child').focus(function(){
    //Do whatever
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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