如何使用jquery onclick更改元素的src

问题描述 投票:1回答:3

我有一个视频播放器,我想要点击它们上面的一些锚点,视频的src被更改。我怎样才能做到这一点?优先选择没有页面刷新

所以看起来应该是这样的:

<a href="#">Video 1</a> <!-- load video1.mp4 -->
<a href="#">Video 2</a> <!-- load video2.mp4 -->
<a href="#">Video 3</a> <!-- load video3.mp4 -->

<video class="myVideo" controls preload="auto" width="600" height="350" >
  <source src="video1.mp4" type="video/mp4" /> <!--this src should be changed by onclick-->
</video>
javascript jquery src
3个回答
1
投票

为您的标记和视频提供数据属性。那你就能做到

<a class="videoLink" href="#" data-url="video1.mp4" >Video 1</a> <!-- load video1.mp4 -->

然后用脚本

$(".videoLink").click(function(e){
  e.preventDefault();
  $('#myVideo source').attr('src', $(this).attr("data-url"));
})

注意 :

某些浏览器在更改src后可能无法更改视频。在这种情况下,您需要调用它们的加载函数。

$('#myVideo').load(); 

1
投票

可以使用data()<a>上存储数据(视频源)。

可以使用attr()更新视频源

$(document).ready(function() {
  $("a").click(function(e) {
    e.preventDefault(); //Prevent the default behaviour of <a>
    var scr = $(this).data("src"); //Get the data-src attribute of <a>
    $(".myVideo source").attr("src", scr); //Assign the value on the video

    var video = $(".myVideo source");
    video.get().load(); //Load the video
    video.get().play(); //Play the video
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" data-src="video1.mp4">Video 1</a>
<!-- load video1.mp4 -->
<a href="#" data-src="video2.mp4">Video 2</a>
<!-- load video2.mp4 -->
<a href="#" data-src="video3.mp4">Video 3</a>
<!-- load video3.mp4 -->

<video class="myVideo" controls preload="auto" width="600" height="350">
  <source src="video1.mp4" type="video/mp4" /> <!--this src should be changed by onclick-->
</video>

文档:

数据:https://api.jquery.com/data/

Attr:https://api.jquery.com/attr/


1
投票
  • 您可以使用正确的视频网址将data-attribute添加到您的链接。
  • 将事件绑定到您的链接。
  • 单击链接时,请阻止默认行为。

$(document).on('click', 'a', function(e) {
  e.preventDefault();
  var source = $(this).data('source');
  console.log('Chaning to "' + source + '"');
  $('.myVideo source').attr('src', source);  
  $('.myVideo').load();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-source='video1.mp4' href="#">Video 1</a>
<!-- load video1.mp4 -->
<a data-source='video2.mp4' href="#">Video 2</a>
<!-- load video2.mp4 -->
<a data-source='video3.mp4' href="#">Video 3</a>
<!-- load video3.mp4 -->

<video class="myVideo" controls preload="auto" width="600" height="350">
  <source src="video1.mp4" type="video/mp4" /> <!--this src should be changed by onclick-->
</video>

Resource

© www.soinside.com 2019 - 2024. All rights reserved.