简体   繁体   中英

Play 'this' parent video with jQuery

I'm using HTML5 video player and custom controls button. Here is my HTML structure:

<video width="840" id="video">

                  <source src="{{box.video}}" type="video/mp4">

                  </video>
                  <div class="controls">
                    <button class="play" ><i class="fa fa-play" aria-hidden="true"></i></button>

JS code:

 $(".play").click(function() {
              $(this).closest("video")[0].play();
            });

When I click play button, its getting undefined error. Whats the problem? How can I fix it?

The issue is because the video is not a parent of the .play button which gets clicked. Given your HTML sample, you need to use closest() to get the .controls div, then prev() to get the video, like this:

$(".play").click(function() {
  $(this).closest('.controls').prev('video')[0].play();
});
<video width="840" id="video">
  <source src="{{box.video}}" type="video/mp4">
</video>
<div class="controls">
  <button class="play">
    <i class="fa fa-play" aria-hidden="true"></i>
  </button>
</div>

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