jQuery/HTML5 modal video if autoplay is present pl

2019-09-02 06:53发布

问题:

This question already has an answer here:

  • How to target autoplay attribute in HTML 5 Video element inside modal 4 answers

To make it easier to understand please take a look at the Codepen: http://codepen.io/hennysmafter/pen/YqmLKR

The codepen is a simpler version of the actual code with only the parts that are necessary!

In the codepen you have two popups one popup has a video element with autoplay and the other has a video element without autoplay

On document ready all video elements on the page are paused this cannot be changed because of other videos in the actual code

Now I just need to have the code adapted so that:

  1. On click popup opens and class is added opened (already there)
  2. If video element inside popup has autoplay then play the video (not working)
  3. Or no autoplay so do nothing

    if ($('.modal-box.opened').find('video').attr(autoplay) == true) {
        $('.modal-box.opened').find('video').each(function() {
          $(this).get(0).play();
    });
    }
    

回答1:

You've two somewhat common mistakes: You only used 1 equals sign in the part where you check if autoplay is true.

A single = is used for setting variables where as two is used for checking equality.

Edit: You are also attempting to use traditional HTML style attribute checking on a jQuery object. To check an attribute in jQuery, you need to use .attr(attributeName)

Therefore, the correct line would be if ($('.modal-box.opened').find('video').attr(autoplay) == true) {