如何减少重复的javascript代码
无论如何我可以减少下面的重复吗?我只显示了两个代码块,但有并将有更多相同的代码块。
我尝试过使用数组和循环,但不幸的是我无法获得有效的示例。先感谢您。
E1 = new Audio('audio/E1.ogg');
E1.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
A1 = new Audio('audio/A1.ogg');
A1.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
编辑:使用下面的乔纳森的代码,我仍然想知道是否可以做相当于:
(E1,A1,x,x,x).addEventListener('ended', callback, false);
// I know this bit of code doesn't work
Is there anyway I can reduce the repetition below? I have only shown two code blocks but there are and will be many more of the same.
I have tried using arrays and loops, but unfortunately I could not get a working example. Thank you in advance.
E1 = new Audio('audio/E1.ogg');
E1.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
A1 = new Audio('audio/A1.ogg');
A1.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
EDIT : Using Jonathan's code below, I am still wondering whether it would be possible to do the equivalent of:
(E1,A1,x,x,x).addEventListener('ended', callback, false);
// I know this bit of code doesn't work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于您的回调是相同的,您可以将它们绑定到一个变量:
Since your callbacks are the same you can just bind them to a variable:
类似的东西
something like
你应该能够做这样的事情。如果您有更多文件,只需将它们的名称添加到数组
fileNames
中即可。audioRefs
最终看起来像......You should be able to do something like this. If you have more files, just add their name into the array
fileNames
.audioRefs
will end up looking like....对于编辑后的问题,如果您使用 Underscore.jseach 函数a> 您可以执行以下操作:
For the edited question, if you use the
each
function from Underscore.js you can do the following: