如何通过数组调用函数? [英] How to call a function by array?

查看:246
本文介绍了如何通过数组调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阵列中有一个视频播放列表。我要在播放选定的视频/video.length(例如2ed,4th,8th等)时调用一个函数(例如,警报 Attention!)。任何解决方案表示赞赏。使用我的JSfiddle中完整的代码

I have a video playlist in array. I want to call a function (e.g. alert "Attention!") when selected videos/video.length are playing (e.g. 2ed, 4th, 8th ...). Any solution is appreciated. Use the complete code from my JSfiddle.

var videoSource = new Array();

videoSource[0]=''; 
videoSource[2]=''; 
videoSource[3]=''; 
videoSource[4]='';
videoSource[5]=''; 

var i = 0;
var videoCount = videoSource.length;
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
videoPlay(0);

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);

function myHandler() {
    i++;
    if(i == (videoCount)){ i = 0; videoPlay(i);}
    else{videoPlay(i);}
}


推荐答案

由于视频开始播放时未阻止代码,因此可以在调用播放之后立即放置逻辑。
检查索引的最简单方法是类似 if(index == 1 || index == 3 || index == 4),等等,但更具可维护性的是将其保留在数组中,例如: if([1,3,4] .indexOf(vidIndex)!= -1)。该数组包含索引。 indexOf 返回数组内部的索引,如果不是,则为 -1 。数组

Since the code is not blocked when the video starts playing, the logic can be placed immediately after play is called. The most simple way to check for indices is something like if(index==1 || index == 3 || index == 4), etc, but a bit more maintainable is keeping it inside an array, such as : if([1,3,4].indexOf(vidIndex) != -1). The array contains the indexes. indexOf returns the index inside the array, which is -1 if it's not inside the array

使用警报的示例:小提琴

更高级的用例是将url的内部对象存储在其中,您还可以为对象分配特定的元数据和行为。例如:对小提琴进行修饰

A bit more advanced use case, would be storing the url's inside objects where you can assign also specific meta data and behaviour to the objects. e.g.: Fiddle with objects

这篇关于如何通过数组调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆