简体   繁体   中英

Jquery multiple selectors within one function using data-attributes

I have a Jquery on() handler with a click event. In the function I get the data attribute that is in the selector's a tag, like so:

$(document.body).on('click', '.video-thumbnail a' ,function(){
  var videoID =  $(this).attr('data-video-id');
  //more data atts etc.
});

My HTML is like so: (times ~ *20)

<div class="block">
    <div class="video-thumbnail">
      <a data-video-id="123"><img></a>
    </div>
    <div class="video-title">
      <a>title</a>
    </div>
    <div class="video-watch">
      <a>Watch</a>
    </div>
</div>

What I want to achieve is that every anchor in the div ".block" have the same click event handler, but I can still use the data-attr from the first anchor (either using this or something else).

So: no matter what anchor the user clicks on within that div; they all execute the same jquery function using the same data-attr.

What is the best way to do this?

Thanks guys.

So, if I'm understanding correctly, you want to attach event handlers to all anchors, but always get the attribute from the .video-thumbnail <div> . You'd be best off using .closest() :

$(document.body).on('click', '.block div a' ,function(){
    var videoID = $(this).closest('.block').find('.video-thumbnail a').attr('data-video-id');
})

Please note the other errors in your code:

  • You need a closing parenthesis at the end of your jQuery
  • You need to close your class attribute on your .video-thumbnail element.

As already mentioned by 76484 it would semantically make much more sense to have each block hold the data-video-id attribute, since that is the upper-most context for each video.

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