javascript - 使 JQuery 函数成为 Plain JS

标签 javascript jquery events listener document

嘿,我有以下函数,它在 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 (evaluating '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;
        }
    })
});

最佳答案

以下应该可以解决问题:

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){});,其中 item 将引用您的项目)。但正如我所说,这不会产生任何影响,因为 nodeList 不是数组。

已更新

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

关于javascript - 使 JQuery 函数成为 Plain JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30758325/

相关文章:

javascript - {} - 0 VS ({} - 0) 在 JavaScript 中

javascript - 搜索存储在同一目录中的 HTML 文件中的关键字

JavaScript 链接多个函数

javascript - 调整图像大小然后上传的图像上传小部件

c# - XmlSerializer 抛出 InvalidOperationException

objective-c - 在 keyDown 事件中获取 modifierFlags 而无需同时按下非修饰键!

javascript - 如何将 JSON 对象转换为 Javascript 数组

javascript - 通过委托(delegate)在jquery中的选定div上应用点击功能

jquery - Owl Carousel - 主题 css 不适用

angular - 当我在组件 A 中收到此函数的事件时,如何调用组件 B 中的函数