使用哈希来改变页面上的视频src

时间:2016-07-01 20:14:39

标签: javascript html video src

使用哈希值更改视频源仅适用于其中一个标记。

例如mywebsite.com/video.php将显示默认视频,如果我转到mywebsite.com/video.php#video1,它将更改为视频-1,但如果我转到mywebsite.com/video.php#video2,则仍会显示视频1。

<script>
// test all possible places hash could be on different browsers
if(window.location.hash){
   hash = window.location.hash;
} else if (document.location.hash){
   hash = document.location.hash;
} else if (location.hash){
   hash = location.hash;
}

// some browsers start the hash with #, remove it for consistency
if(hash.substring(0,1) == '#'){
    hash = hash.substring(1,hash.length);
}

if(hash = '#video1'){
  document.getElementById('myVideo') .src=a = "http://mywebsite.com/videos/video-1.mp4";
}

if(hash = '#video2'){
  document.getElementById('myVideo') .src=a = "http://mywebsite.com/videos/video-2.mp4"";
}
</script>
<video id="myVideo" controls>
     <source src="http://mywebsite.com/videos/video-default.mp4">
    </video>

我该如何解决这个问题?有没有更好的方法来使用某种id更改src路径?

1 个答案:

答案 0 :(得分:1)

您应该使用= ==。即使您在#的开头删除了hash,您仍然会将其包含在比较字符串中。

if (hash == 'video1') {
  document.getElementById('myVideo') .src=a = "http://mywebsite.com/videos/video-1.mp4";
} else if (hash == 'video2') {
  document.getElementById('myVideo') .src=a = "http://mywebsite.com/videos/video-2.mp4"";
}
相关问题