I'm writing a routine in Javascript that iterates through all audio elements in a HTML page. All elements are marked with ID in the form of 'track_[nr]' and each one has a customized button which toggles play/pause marked with ID 'control_[nr]'.
Now I want to automate an onclick event on each control element by iterating through all elements and assigning a onclick function.
I came up with following code, but the "for" loop doesn't behave like I'd expect.
"document.writeln(j)" always prints 5 (i have currently 5 audio elements), no matter on which control element i click. I would expect it to write "0" when you click on "control_0", "1" when clicking on "control_1", etc.
Any help is much appreciated!
<script type='text/javascript'>
var audio = new Array();
var ctrl = new Array();
var i = 0;
do {
audio[i] = document.getElementById('track_'+i), ctrl[i] = document.getElementById('control_'+i);
i++;
} while(audio[i-1]);
tracks=i-1;
for (var j = 0; j < tracks; j++) {
ctrl[j].onclick = function () {
document.writeln(j);
}
}
</script>
Regards