将事件侦听器添加到 javascript 中的音频 HTML5 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6312714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:13:47  来源:igfitidea点击:

Adding event listener to audio HTML5 tag in javascript

javascripthtmlaudioevent-handling

提问by Zeta

Hi I'm creating a new audio tag element in Javascript this is the code:

嗨,我正在用 Javascript 创建一个新的音频标签元素,这是代码:

var audio = document.createElement("audio");
audio.setAttribute("id","myid");
audio.setAttribute("autoplay","autoplay");
document.body.appendChild(audio);

before appending it to the body, I'd like to place an onended event handler, I tried something like this:

在将它附加到正文之前,我想放置一个 onended 事件处理程序,我尝试了这样的事情:

audio.onended = foo;

where foo is something like: function foo(){alert('Hola')}

其中 foo 类似于: function foo(){alert('Hola')}

and

audio.setAttribute("onended","foo()");

in both case it didn't work. In the first case the audio tag is appended without any onended event handler; while in the second case the audio tag is appended, the onended event is on the attributes but it does not fire.

在这两种情况下,它都不起作用。在第一种情况下,音频标签是在没有任何 onended 事件处理程序的情况下附加的;而在第二种情况下,附加了音频标签,但 onended 事件位于属性上,但不会触发。

does someone have any idea?

有人有任何想法吗?

thanks in advance.

提前致谢。

-z-

-z-

回答by Variant

try:

尝试:

audio.addEventListener('ended', foo);

This is the correct and standard method to add event listeners.

这是添加事件侦听器的正确且标准的方法。

回答by user1217010

First, make sure whether audio element has the event before you use it, suppose the HTMLAudioElementis audio, you can test it like this audio.hasOwnProperty('onended')

首先,在使用之前确定audio元素是否有事件,假设HTMLAudioElement是音频,可以这样测试audio.hasOwnProperty('onended')

Based on my browser, it doesn't support.

基于我的浏览器,它不支持。

回答by Adil Malik

I found this very helpful jsfiddle from Google: http://jsfiddle.net/aarongloege/fzXsT/light/

我从 Google 找到了这个非常有用的 jsfiddle:http: //jsfiddle.net/aarongloege/fzXsT/light/

{Code on /*jsFiddle*/}