K
K
KianGreenMoon2018-02-19 04:14:59
JavaScript
KianGreenMoon, 2018-02-19 04:14:59

Why does JS misunderstand the pressed button tag of a modal from a loop?

Below is the html markup mixed with Jinja:

{% for Videos in object_list %}
<!-- Button of Modal -->
        <button class="btn btn-primary btn-md" data-toggle="modal" data-target="#videoOn{{Videos.id}}">
        			Запустить
      			</button>
      </div>


      		<!-- Modal видео -->
      <div class="modal fade" id="videoOn{{Videos.id}}" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-body" style="padding: 0px;">
              <div class='embed-responsive embed-responsive-16by9'>
              	<iframe class='embed-responsive-item' src="{{Videos.url}}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
            	</div>
            </div>
          </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
      </div><!-- /.modal -->
{% endfor %}

And this is the JS included at the end:
(function(){
  // Ссылка на кнопку открытия модального окна
  var trigger = $('[data-toggle="modal"]');
  // Ссылка на iframe с видеороликом
  var iframe = $(trigger.data('target') + ' iframe');
  // Строка с адресом видео на 
  var videoSrc = iframe.attr('src');
  // При клике по кнопке добавляем к атрибуту src строку '?autoplay=1'
  trigger.on('click', function() {
    iframe.attr('src', videoSrc + '?autoplay=1');
  });
  // При скрытии модального окна
  $(trigger.data('target')).on('hidden.bs.modal', function () {
    iframe.attr('src', videoSrc);
  });
})();

I want to have a database of YouTube videos, which I visualize as buttons that, when clicked, open a modal window with autoplay, and when the modal window is exited, the playback would be interrupted. However, trigger.data('target') only gets the value of the last data-target from the loop, no matter what button I press. Total: I click on the first video, the first video is displayed, but not autoplayed. However, the second video is autoplayed (the sound goes on), and when the modal window is closed, the playback continues, as if I had not closed the modal window. But with the last (second) video in the database table, everything works as it should.
In short, I don’t know js much, so I’ll be grateful for a detailed answer, alas, I didn’t find it myself. I want to know why and how to fix it.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question