如何使用Javascript将Google Analytics事件添加到所有<audio>标记?

时间:2017-01-05 22:39:47

标签: javascript audio google-analytics

我需要为所有音频代码添加Google Analytics事件。

如果所有音频标签都属于特定类,我可以这样做:

<script>
/* a test script */
$(function() {
  // Every button with the audioClass class can execute the function.
  $( "audioClass" ).on("click", (function() {
    ga('send', 'event', 'audioclass', 'clicked', 'test');
    });
  });
</script>

但是可以使用音频标签(即没有类名)吗?

<script>
/* 2nd test script */
$(function() {
  // Every audio tag will hopefully execute the function.
  $("audio").on("click", function() {
    ga("send", "event", "audio", "clicked", "test");
    });
  });
</script>

我在这里找到了类似的答案:Adding play buttons for all audio tags on a page 但我无法看到如何使用它:

  

$(&#34; audio&#34;).each(function(index){

在我的代码中。

1 个答案:

答案 0 :(得分:0)

你正在寻找onplay活动:

&#13;
&#13;
    $("audio").on("play", function() {
       ga("send", "event", "audio", "clicked", "test");
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio controls>
  <source src="http://www.noiseaddicts.com/samples_1w72b820/280.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio>
&#13;
&#13;
&#13;