Как я могу применить javascript сразу к нескольким элементам с разными идентификаторами?

#javascript #jquery #performance #embed

#язык JavaScript #jquery #Производительность #Внедрить

Вопрос:

У меня есть этот код, который позволяет мне останавливать воспроизведение видео на YouTube после нажатия кнопки. Вот пример:

 //Hotel Post lt;scriptgt;  $(document).ready(function() {  // set unique id to videoplayer for the Webflow video element  var src = $('#videoplayer').children('iframe').attr('src');   // when object with class open-popup is clicked...  $('.open-popup.left').click(function(e) {  e.preventDefault();  // change the src value of the video  $('#videoplayer').children('iframe').attr('src', src);  $('.popup-bg').fadeIn();  });   // when object with class close-popup is clicked...  $('.close-modal-button').click(function(e) {  e.preventDefault();  $('#videoplayer').children('iframe').attr('src', '');  $('.popup-bg').fadeOut();  });  }); lt;/scriptgt;  //Gans to go lt;scriptgt;  $(document).ready(function() {  // set unique id to videoplayer for the Webflow video element  var src = $('#videoplayer2').children('iframe').attr('src');   // when object with class open-popup is clicked...  $('.open-popup.left').click(function(e) {  e.preventDefault();  // change the src value of the video  $('#videoplayer2').children('iframe').attr('src', src);  $('.popup-bg').fadeIn();  });   // when object with class close-popup is clicked...  $('.close-modal-button').click(function(e) {  e.preventDefault();  $('#videoplayer2').children('iframe').attr('src', '');  $('.popup-bg').fadeOut();  });  }); lt;/scriptgt;  

У меня на сайте около 14 подобных видео, встроенных на мой сайт, и это замедляет работу, потому что у меня есть один из этих сценариев для каждого видео. Есть ли какой-нибудь способ выбрать несколько идентификаторов сразу или что-то в этом роде? Итак, у меня есть один сценарий для всех видео?

Я был бы признателен за помощь. Большое спасибо. Пабло

Ответ №1:

Один из способов-установить для всех видео общее имя класса, например video , и сохранить переменную src в атрибуте данных.

 $(document).ready(function() {  // set unique id to videoplayer for the Webflow video element   $('.video').each(function() {  let src = $(this).children('iframe').attr('src');  $(this).attr('data-src', src);  })   // when object with class open-popup is clicked...  $('.open-popup.left').click(function(e) {  e.preventDefault();  // change the src value of the video  $('.video').each(function() {  $(this).children('iframe').attr('src', $(this).data('src'));  $('.popup-bg').fadeIn();  });   // when object with class close-popup is clicked...  $('.close-modal-button').click(function(e) {  e.preventDefault();  $('.video').each(function() {  $(this).children('iframe').attr('src', '');  $('.popup-bg').fadeOut();  });  });