【问题标题】:Making JQuery function Plain JS [duplicate]制作JQuery函数Plain JS [重复]
【发布时间】:2015-06-10 13:50:06
【问题描述】:

嘿,我有以下在 JQuery 中运行良好的函数,但由于许多原因,我需要在纯 JS 中使用它。

$('audio').on("play pause ended", function () {
    document.title = document.title.replace("\u25B6", "")
    $("audio").each(function (index) {
        if (!this.paused) {
            document.title = "\u25B6 " + document.title.replace("\u25B6 ", "")
            return false;
        }
    })
});

我尝试将其转换为纯 JS(见下文),但它只是出现以下错误:TypeError: undefined is not a function (evalating 'sound.addEventListener')

var sound = document.getElementsByTagName('audio');
sound.addEventListener('play pause ended', function () {
    document.title = document.title.replace('\u25B6', '')
    sound.each(function (index) {
        if (!this.paused) {
            document.title = '\u25B6 ' + document.title.replace('\u25B6 ', '')
            return false;
        }
    })
});

【问题讨论】:

  • 错误告诉你sound是未定义的。
  • Youre getElementsByTagName 返回一个 nodeList,而不是 HTMLElementDOMNode,您需要遍历该列表并将侦听器附加到您想要侦听它的任何/所有元素.
  • 虽然这是正确的,但我之前的行是 var sound = document.getElementsByTagName('audio')[0];哪个显示单个 HTMLElement 正确?并且同样的错误适用。

标签: javascript jquery events listener document


【解决方案1】:

以下应该可以解决问题:

var sounds = document.getElementsByTagName('audio');
/* Loop through the nodelist - this is **not** an array */
for(var i = 0; i < sounds.length; i++){
    /* Get the item in your nodelist. This **is** an element. */
    var sound = sounds.item(i);
    /* Now add your event listener here - You can only add one at a 
     * time, though. So I decided to make the event a separate  
     * function and attach it multiple timers. */
    function eventHandler(){
        document.title = document.title.replace('\u25B6', '')
        if (!sound.paused) {
            document.title = '\u25B6 ' + document.title.replace('\u25B6 ', '')
            return false;
        }
    }
    sound.addEventListener('play', eventHandler, false);
    sound.addEventListener('pause', eventHandler, false);
    sound.addEventListener('ended', eventHandler, false);
}

两件事:document.getElementsByTagName 返回一个 不是 数组的 HTMLNodeList。它可以循环,因为它有一个length属性,但它不能使用forEach(因为它还有一个叫做item的函数,用于获取节点列表提供的索引处的元素)。

其次,this 没有在forEach 中引用您的项目,您需要将参数传递给您可以引用的forEach 函数(又名array.forEach(function(item){});,您的项目将被@987654330 引用@)。但就像我说的,这不会有什么不同,因为 nodeList 不是数组。

更新

我突然想到有一种简单的方法可以附加所有事件,因此我对其进行了适当的修改。

【讨论】:

  • 太棒了,太棒了——你是救生员:)
  • 我有一个问题,你知道我怎样才能将它应用于 iFrame 中使用的音频标签吗?
  • 我认为您可以(我说 可以,因为我没有尝试过)使用 iframe,然后深入研究它的内容和正文,但我不确定。看看这个,希望它对你有所帮助:stackoverflow.com/questions/926916/…
猜你喜欢
  • 1970-01-01
  • 2017-05-20
  • 2021-12-06
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多