Reputation: 213
When data-word is called I want a sound and an image to show and play. I have tried many different ways but can't figure it out.
Here is one way...
for(i = 0; i < ul.children.length; ++i){
listOfWords[ul.children[i].getAttribute("data-word")] = ul.children[i].getAttribute("data-pic", "data audio");
}
console.log(listOfWords);
I have also tried...
for(i = 0; i < ul.children.length; ++i){
listOfWords[ul.children[i].getAttribute("data-word")] = ul.children[i].getAttribute("data-pic");
listOfWords[ul.children[i].getAttribute("data-word")] = ul.children[i].getAttribute("data-audio");
}
console.log(listOfWords);
But no such luck.
The second way does the bottom but not the top, I need both the data-audio and the data-pic when the data-word is called.
Can anyone help?
HTML...
<ul style="display:none;" id="wordlist">
<li data-word="mum" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://pixabay.com/static/uploads/photo/2012/04/13/00/06/head-31117_640.png"></li>
<li data-word="cat" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://pixabay.com/static/uploads/photo/2012/05/03/23/13/cat-46676_640.png"></li>
<li data-word="dog" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://pixabay.com/static/uploads/photo/2012/05/02/21/14/gray-46364_640.png"></li>
<li data-word="bug" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav" data-pic="http://pixabay.com/static/uploads/photo/2012/04/16/12/17/black-35741_640.png"></li>
<li data-word="log" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://pixabay.com/static/uploads/photo/2012/04/13/11/18/fire-31929_640.png"></li>
<li data-word="dad" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav" data-pic="http://pixabay.com/static/uploads/photo/2012/04/13/00/05/old-31110_640.png"></li>
Upvotes: 0
Views: 103
Reputation: 43087
With jQuery, you can use .each()
to iterate over the list items and .data()
to retrieve data attribute values.
var listOfWords = [];
$("#wordlist li").each(function(index, item) {
// where liData is { word: "a", audio: "b", pic: "c" }
var liData = $(item).data();
listOfWords[liData.word] = liData;
console.log("word: " + liData.word + ", audio: " + liData.audio + ", pic: " + liData.pic);
});
Upvotes: 0
Reputation: 150040
Something like this:
for(i = 0; i < ul.children.length; ++i){
listOfWords[ul.children[i].getAttribute("data-word")] = {
"pic" : ul.children[i].getAttribute("data-pic"),
"audio" : ul.children[i].getAttribute("data-audio")
};
}
Then for a given item in the listOfWords
object you can do:
var currentWord = "cat"; // set current word key somehow, then:
console.log(listOfWords[currentWord].pic);
console.log(listOfWords[currentWord].audio);
With jQuery:
var listOfWords = {};
$("#wordlist li").each(function() {
var $item = $(this);
listOfWords[ $item.attr("data-word") ] = {
pic : $item.attr("data-pic"),
audio : $item.attr("data-audio")
};
});
Upvotes: 2