如何将动态元素 ID 与 JPlayer 的 Javascript onClick 事件一起使用

How to use dynamic element ID with Javascript onClick event for JPlayer

我已经尝试自己解决这个问题,而且我通常不会停下来,直到我弄清楚一些事情。然而,这让我难住了。

我们的独特情况涉及使用 WooCommerce 产品循环,在我们的主页上显示许多产品。当用户将鼠标悬停在产品图片上时,会显示一个带有播放按钮和一些其他有用图标的叠加层。

单击此播放按钮后,我们的 JPlayer 应该只播放关联的 mp3 文件。根据显示的产品,我已经弄清楚如何让它播放 mp3 文件。然而,我很快意识到我必须为显示的每个产品指定一个唯一的 ID,否则播放器将不会在同一页面上播放多首歌曲。希望我还没有失去任何人。

所以我想,为什么不使用 post id 作为唯一标识符呢?下面是我用于播放按钮覆盖的 link 标签。

<a id="myPlayButton-<?php the_id(); ?>" data-mp3file="<?php echo $file; ?>" data-mp3title="<?php the_title(); ?>" href="#">
<i class="icon-control-play i-2x"></i>
</a>

如您所见,我正在唯一标识此按钮(以及循环中的每个按钮),它生成一个 ID,例如:"myPlayButton-1234"

我的问题是,一旦我有了这个新 ID,我就不知道如何在我的 javascript 代码中使用这个唯一 ID。如果我简单地定义一个普通 ID(类似于 "myPlayButton"),代码就可以正常工作。但它只会播放循环中的第一首歌曲。我不知道如何在我的代码中使用上面的 ID。

这是有效的 jplayer 代码,但只播放循环中的第一首歌曲(因为每个元素的 ID 不是唯一的):

<script type="text/javascript">
$("#myPlayButton").click(function () {
             var playbutton = document.getElementById("myPlayButton");
             var mp3id = playbutton.getAttribute('data-mp3file');
             var songtitle = playbutton.getAttribute('data-mp3title');
                 $("#jplayer_N").jPlayer("setMedia", {mp3: mp3id, title: songtitle}).jPlayer("play");
         });
</script>

这是我们尝试使用的 jplayer 代码:

<script type="text/javascript">
$("<?php echo '#myPlayButton-'.the_id(); ?>").click(function () {
             var playbutton = document.getElementById("<?php echo 'myPlayButton-'.the_id(); ?>");
             var mp3id = playbutton.getAttribute('data-mp3file');
             var songtitle = playbutton.getAttribute('data-mp3title');
                 $("#jplayer_N").jPlayer("setMedia", {mp3: mp3id, title: songtitle}).jPlayer("play");
         });
</script>

我在某处读到,我可以按照上面的方式在我的 javascript 中输入 php 代码。但是,播放按钮根本不起作用。我已经尝试了很多不同的方法来将唯一 ID 放入我的 JS,但没有任何效果。

我需要一种方法将唯一 ID 传递给脚本,以便我可以让播放按钮在循环中的每个 post/product 上工作。此外,如果它有助于了解,我在页脚中的结束 BODY 标记之前包含了这个小脚本。如果我把它放在其他地方,它就不起作用。也许我没有在正确的地方使用它?

谁能指导我正确的方向?如果我没有包含足够的信息,我深表歉意。我是这个网站的新手。我已经潜伏了一段时间。

非常感谢!

使用 class 而不是 id。看看这是否有效:

<a class="mybutton" data-mp3file="<?php echo $file; ?>" data-mp3title="<?php the_title(); ?>" href="#">
<i class="icon-control-play i-2x"></i>
</a>

<script type="text/javascript">
$(".mybutton").click(function () {
    // Using $(this) targets the specific clicked element
    var playbutton  =   $(this);
    // Append your object and use .data()
    var mp3id       =   playbutton.data('mp3file');
    // Append your object and use .data()
    var songtitle   =   playbutton.data('mp3title');
    // Should need no change to this line
    $("#jplayer_N").jPlayer("setMedia", { mp3: mp3id, title: songtitle }).jPlayer("play");
});
</script>