Problem when using echo'd ++$value in javascript as part of a html5 audio player page

 ̄綄美尐妖づ 提交于 2020-05-16 04:20:28

问题


I have been making myself a 'soundboard' that populates a custom HTML5 audio player for each mp3 file it finds in a directory. Now that side of it is all working exactly as I expected but my problems started when I have attempted to add a custom timer which uses javascript.

For each player, I was able to make custom controls and make the variables all marry up with things like

<audio id="player<?php echo $count1++;?>" src="audio/<?php echo rtrim($file, " "); ?>"></audio>

So using PHP echo a lot to repeat the players and controls but with new ids and as mentioned this is all functioning great but when I try and apply the same to a javascript snippet I'm using this is where my problems start as the ++ seems to be going a bit Pete Tong and is resulting in 2,4,6,8 or 3,6,9,12 when I was expecting 1,2,3,4

Here is the js code in question

// Get the audio element with id from variable
var count10 = "<?php echo $count10 ;?>";
var aud = document.getElementById("player" + count10);

    // Assign an ontimeupdate event to the audio element, and execute a function if the current playback position has changed
    aud.ontimeupdate = function() {myFunction()};

    var count11 = "<?php echo $count11 ;?>";
    function myFunction() {
      // Display the current position of the audio in a p element with id from var
      document.getElementById("time" + count11).innerHTML = aud.currentTime;
    }

To be clear my issue is adding a timer which should appear under each play/stop button once you hit play, this currently only works for the 1st player instance in my pastebin code above.

I've spent 4-5 hours now on nothing but trying to solve this without having to ask on here and have got to the point Its no longer fun! Please help, many thanks.


回答1:


Rather than keep a separate count to link the the item, you can use the foreach loop to give you the item index...

So when you do

foreach ($files as $file) {

you can use

foreach ($files as $id => $file) { 

and then use

echo $id;

inside the loop to output the corresponding ID.



来源:https://stackoverflow.com/questions/61193307/problem-when-using-echod-value-in-javascript-as-part-of-a-html5-audio-player

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!