我创建了以下代码,以便在悬停时播放视频:
var player = [];
var el_number;
function onYouTubePlayerAPIReady() {
var players = $(".video");
for (var i = 0; i < players.length; i++) {
el_number = $(players[i]).parent().parent().index();
player[i] = new YT.Player(players[i], {
events: {
'onReady': onPlayerReady(i, el_number)
}
});
}
}
function onPlayerReady(number, elnumber) {
$(".article:eq("+elnumber+")").on({
'mouseover': function() {
player[number].playVideo();
},
'mouseout': function() {
player[number].pauseVideo();
}
});
}
<script src="https://www.youtube.com/iframe_api"></script>
<!-- Videos look like this: -->
<iframe class='video' src='https://www.youtube.com/embed/(video_id)?controls=0&showinfo=0&disablekb=1&fs=0&iv_load_policy=3&&enablejsapi=1' frameborder='0' allowfullscreen></iframe>
它工作得非常好,但是在加载脚本一段时间后,它会在控制台中显示这个错误:
Uncaught TypeError: Cannot read property 'apply' of undefined www-widgetapi.js:65
at K.g.I (www-widgetapi.js:65)
at W.g.l (www-widgetapi.js:114)
at W.g.J (www-widgetapi.js:127)
at S.g (www-widgetapi.js:143)
at k (www-widgetapi.js:95)
我踩了Opera和Edge,没有错误。禁用每个扩展后,Chrome中仍存在此问题。这里问题的根源是什么?
答案 0 :(得分:3)
我认为这是你的回调定义的一个问题:
onPlayerReady(i, el_number)
onPlayerReady
将事件数据作为参数。要获得播放器,您可以调用event.target
并在此对象中存储一些数据
例如:
var player = [];
function onYouTubePlayerAPIReady() {
var players = $(".video");
for (var i = 0; i < players.length; i++) {
el_number = $(players[i]).parent().parent().index();
player[i] = new YT.Player(players[i], {
events: {
'onReady': onPlayerReady
}
});
player[i].el_number = el_number;
}
}
function onPlayerReady(event) {
console.log("event.target.el_number : " + event.target.el_number);
$(".article:eq(" + event.target.el_number + ")").on({
'mouseover': function() {
event.target.playVideo();
},
'mouseout': function() {
event.target.pauseVideo();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<!-- Videos look like this: -->
<iframe class='video' src='https://www.youtube.com/embed/B_hLfhccYf0?controls=0&showinfo=0&disablekb=1&fs=0&iv_load_policy=3&enablejsapi=1' frameborder='0' allowfullscreen></iframe>
你可以找到一个jsfiddle here