javascript - 仅播放顶部的 audio_tag 按钮

标签 javascript ruby-on-rails audio

我开始在我的网站上添加音频;我有previously在我的一个 View 中实现了带有字形按钮的audio_tag。在不同的 View 中,我试图列出所有单词对象,并且我希望有一个按钮来播放每个相关的音频。截至目前,此功能仅适用于此 View 中列出的第一个单词对象。如何让按钮在单击 View 中的所有对象时播放声音?

类(class)展示 View :

<div class ="col-xs-10 col-xs-offset-1">
  <h3>Vocabulary</h3>
  <br>
  <ul>
    <% @lesson.words.each do |word| %>
      <li> 
        <%= image_tag word.image_url(:thumb) if word.image? %> 

        <b><%= word.term %></b> 

        <%= audio_tag word.sound, class: "audio-play" %>
        <button type="button" class="btn btn-default", id="audioButton">
          <span class="glyphicon glyphicon-play" aria-hidden="true"></span>
        </button>

        <i>(<%= word.reference %>)</i>

      </li>
      <br>
    <% end %>
  </ul>
</div>

application.js:

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require_tree .

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

最佳答案

为每个人提供自己唯一的 ID。

在 html 中,id 必须是唯一的。例如“#audioButton1”“#audioButton2”等...或者,不要使用ID,使用类名例如class =“btn btn-default audio-button”然后$(“.audio-button").on("点击", function()

关于javascript - 仅播放顶部的 audio_tag 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37801481/

相关文章:

ruby-on-rails - 使用 CloudFlare、Heroku 和 RoR 时如何设置真实 IP 地址?

mysql - Rails 3 两个表之间的查询

ruby-on-rails - Ruby on Rails 中 User.new 的解释? (来自 Michael Hartl 的教程)

networking - 使用 ffmpeg 录制/捕获不连续的音频流

java - 如何减少Java中的振幅数组大小?

c# - 在 C# 中播放声音 byte[]

javascript - --prod 在构建 Ionic 3 应用程序时不工作

javascript - 如何从 C++ 插件中的 'MediaStream' 对象读取音频数据

javascript - 多个 Div 的动画

javascript - 为什么 js 无法理解字符串 '&lt;/script&gt;'?