我刚刚开始使用jquery-3.3.1和我的onload();功能不再起作用了。我知道这已更新,所以我将window.onload = function(e)
更改为$(window).on("load", function (e)
,但无法正常工作......这段代码有什么问题?我现在如何调用加载函数?
$(window).on("load", function (e) {
var videoSource = new Array();
videoSource[0] = 'video1.mp4';
videoSource[1] = 'video2.mp4';
var i = 1; // define i
var videoCount = videoSource.length;
function videoPlay(videoNum) {
document.getElementById("myVideo").setAttribute("src", videoSource[videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
videoPlay(0); // play the video
function myHandler() {
i++;
if (i == (videoCount - 1)) {
i = -1;
videoPlay(0);
} else {
i = 0;
videoPlay(1);
}
}
})
这是我的HTML:
<video playsinline autoplay muted id="myVideo" type="video/mp4" onload="onload();" poster="poster.png"></video>
已解决:问题源于此问题,我在{(1)}({1}}之前使用此window.onload = function()
...对不起的家伙,我非常喜欢javascript,刚刚学习了这个基础知识语言。现在您可以使用所有解决方案,非常感谢您的所有回复!
答案 0 :(得分:3)
由于除了等待加载文档之外你没有使用jQuery,所以只需将它替换为普通的js
window.onload = function() {
// let's go!
}
请注意,许多浏览器(如safari)会阻止视频的自动播放。一旦其他浏览器采用此功能,您的代码将不再起作用。
答案 1 :(得分:2)
使用 $(document).ready()代替$(window).on("load", function...
$(document).ready(function() {
console.log("ready!");
});
OR 简写:
$(function() {
console.log("ready!");
});
在您的情况下将是:
$(function() {
var videoSource = new Array();
videoSource[0] = 'video1.mp4';
videoSource[1] = 'video2.mp4';
var i = 1; // define i
var videoCount = videoSource.length;
function videoPlay(videoNum) {
document.getElementById("myVideo").setAttribute("src",
videoSource[videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
videoPlay(0); // play the video
function myHandler() {
i++;
if (i == (videoCount - 1)) {
i = -1;
videoPlay(0);
} else {
i = 0;
videoPlay(1);
}
}
})
More on this subject. 同时结帐 how to handle Video Element Events using jQuery 。
答案 2 :(得分:1)
不使用$(window).on("load")...
,而是使用$(document).ready(function)
代替
此外,值得注意的是,很多浏览器现在都禁用自动播放,因此请注意那个。
$(document).ready(function (e) {
var videoSource = new Array();
videoSource[0] = 'video1.mp4';
videoSource[1] = 'video2.mp4';
var i = 1; // define i
var videoCount = videoSource.length;
function videoPlay(videoNum) {
document.getElementById("myVideo").setAttribute("src", videoSource[videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
videoPlay(0); // play the video
function myHandler() {
i++;
if (i == (videoCount - 1)) {
i = -1;
videoPlay(0);
} else {
i = 0;
videoPlay(1);
}
}
})