我试着自己弄清楚这个问题,我通常不弄清楚就不会停下来。然而,这把我难住了。
我们的独特情况涉及使用WooCommerce产品循环,在我们的主页上显示许多产品。当用户将鼠标放在产品图像上时,会显示一个覆盖层,其中包含播放按钮和其他一些有用的图标。
在点击这个播放按钮后,我们的JPlayer应该简单地播放相关的mp3文件。根据显示的产品,我已经弄清楚了如何让它播放mp3文件。然而,我很快意识到我必须为显示的每个产品指定一个唯一的ID,否则播放器将不会在同一页面上播放多首歌曲。希望我没有失去任何人。所以我想,为什么不使用post id作为唯一标识符?下面是我用于播放按钮叠加的链接标签。
<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到脚本,这样我就可以得到播放按钮的工作在每个岗位/产品的循环。此外,如果它有助于了解,我包括这个小脚本在结束BODY标签之前在我的页脚。如果我把它放在其他地方,它就不起作用了。也许我用错地方了?
有谁能给我指路吗?如果我没有包含足够的信息,我道歉。我是这个网站的新手。我做潜伏者已经有一段时间了。非常感谢!
使用一个类代替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>