audio_tag为不同的按钮播放相同的文件 [英] audio_tag plays same file for different buttons

查看:96
本文介绍了audio_tag为不同的按钮播放相同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是刚开始使用audio_tag的人;我正在尝试使用一组按钮来播放简短的音频文件.我正在帖子中实现此功能.我目前有两个带有关联按钮的音频标签,它们应该播放不同的文件.但是,两个按钮都播放第一个音频文件.我为每个按钮分配了不同的ID,但这无济于事.如果删除第一个文件,则第二个按钮将播放预期的文件. (mp3文件位于/public/audios中.)

I'm new at using audio_tag; I'm trying to use a set of buttons to play short audio files. I'm going off this post to implement this feature. I currently have two audio tags with associated buttons, which should play different files. However, both buttons play the first audio file. I'm assigning different IDs to each button, but this is not helping. If I remove the first file, then the second button plays the expected file. (The mp3 files are located in /public/audios).

如何将正确的文件关联到其按钮?

How can I go about associating the correct file to its button?

视图:

<%= audio_tag "a.mp3", class: "audio-play" %>
<button type="button" class="btn btn-primary btn-lg", id="audioButtonA">A</button>

<br>

<%= audio_tag "e.mp3", class: "audio-play" %>
<button type="button" class="btn btn-primary btn-lg", id="audioButtonE">E</button>

application.js:

application.js:

jQuery(document).ready(function() {
$("#audioButtonA").on("click", function() {
        $(".audio-play")[0].currentTime = 0;
        return $(".audio-play")[0].play();
      });
});

jQuery(document).ready(function() {
$("#audioButtonE").on("click", function() {
        $(".audio-play")[0].currentTime = 0;
        return $(".audio-play")[0].play();
      });
});

推荐答案

通过使用$(".audio-play")[0].play(),您总是选择与文件(a.mp3)相同的元素,通常是类audio-play的第一个元素.为了实现您的目标,只需单击按钮,您就必须选择一个之前的元素,它是一个音频标签,如下所示:

By using $(".audio-play")[0].play() you are always selecting the same element with the file (a.mp3), generally the first element with the class audio-play. To achieve your aim, on button click you have to select the previous element wich is an audio tag like so:

$("#audioButtonE").on("click", function() {
    var audio = $(this).prev()[0];
    audio.currentTime = 0;
    return audio.play();
});

这篇关于audio_tag为不同的按钮播放相同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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