简体   繁体   中英

(jQuery) Apply the title that is inside an element as an aria-label to the link that is inside the div and does not contain an aria label

HTML

<div class="box-container">
 <a href="#"></a>
 <h3 class="box-title">Title 1</h3>
</div>
<div class="box-container">
 <a href="#"></a>
 <h3 class="box-title">Title 2</h3>
</div>
    <div class="box-container">
 <a href="#"></a>
 <h3 class="box-title">Title 3</h3>
</div>

jQuery

 $('a:not([aria-label])').attr('aria-label', function() {
      var txt = $(".box-container > .box-title").text();
      $(this).attr("aria-label", txt);
  });

The problem is that the above div appears 3 times inside the whole page, so the code above will return and apply as an aria-label in the link, all the titles that have these classes. Example: aria-label="Title element 1Title element 2Title element3"

So I am trying to figure out why the above does not apply to the link of the div, the specific.box-title class for each div, only.

What I try to achieve and $(this) does not work properly:

  <div class="box-container">
     <a href="#" aria-label="Title 1"></a>
     <h3 class="box-title">Title 1</h3>
  </div>
  <div class="box-container">
     <a href="#" aria-label="Title 2"></a>
     <h3 class="box-title">Title 2</h3>
  </div>
  <div class="box-container">
     <a href="#" aria-label="Title 3"></a>
     <h3 class="box-title">Title 3</h3>
  </div>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="box-container"> <a href="#"></a> <h3 class="box-title">Title 1</h3> </div> <div class="box-container"> <a href="#"></a> <h3 class="box-title">Title 2</h3> </div> <div class="box-container"> <a href="#"></a> <h3 class="box-title">Title 3</h3> </div> <script> $('a:not([aria-label])').attr('aria-label', function() { var txt = $(this).parent().find(".box-title").text(); $(this).attr("aria-label", txt); }); </script>

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