问题
HTML:
<div class="source" id="source_one" onclick="chnageToSourceTwo()">
Source 1
</div>
<video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="none" width="640" height="360" poster="" data-setup="{}">
<source src="example_video_1.mp4" type='video/mp4' />
</video>
Script:
function chnageToSourceTwo() {
document.getElementById("example_video_1").src="example_video_2.mp4";
}
The video source is not changing after clicking on div. I am using the Video.js plugin to add video player to my webpage.
Does anyone know how to change source of video onclick?
jsFiddle http://jsfiddle.net/ah1fj7te/
回答1:
It would be easier is to give your <source>
object an ID. and reference the object by the ID using document.getElementById and document.addEventListener
Change your HTML:
<div class="source" id="source_one">Source 1</div>
<video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="none" width="640" height="360" poster="" data-setup="{}">
<source id="source_video" src="example_video_1.mp4" type='video/mp4' />
</video>
<script>
document.getElementById('source_one').addEventListener('click', function() {
document.getElementById('source_video').src = 'example_video_2.mp4';
});
</script>
回答2:
I noticed you tagged this as jQuery, so here is how you would implement this in jQuery.
$("#example_video_1 source").attr("src", "example_video_2.mp4");
回答3:
Change this line:
document.getElementById("example_video_1").src="example_video_2.mp4";
With this:
document.getElementById("example_video_1").getElementsByTagName('source')[0].src="example_video_2.mp4";
回答4:
Here is a DEMO
And here some code:
var a = document.getElementById('source_one');
a.addEventListener('click',function() {
document.getElementById("example_video_1").children[0].src="example_video_2.mp4";
a.innerHTML = 'Source 2';
alert(document.getElementById('example_video_1').children[0].src); // just to show that it is changed...
});
If you want to be able to toggle both videos, use this:
DEMO
var a = document.getElementById('source_one');
var b = document.getElementById("example_video_1");
a.addEventListener('click',function() {
if (document.getElementById("example_video_1").children[0].src == 'http://fiddle.jshell.net/_display/example_video_2.mp4') // replace with real url
{
document.getElementById("example_video_1").children[0].src="example_video_1.mp4";
a.innerHTML = 'Source 1';
}
else {
document.getElementById("example_video_1").children[0].src="example_video_2.mp4";
a.innerHTML = 'Source 2';
}
});
来源:https://stackoverflow.com/questions/27140952/how-to-change-video-source-onclick