0

当调用数据字时,我想要显示和播放声音和图像。我尝试了许多不同的方法,但无法弄清楚。

这是一种方法...

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);

我也试过...

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);

但没有这样的运气。

第二种方法是底部而不是顶部,当调用数据字时,我需要数据音频和数据图片。

任何人都可以帮忙吗?

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>

4

2 回答 2

2

像这样的东西:

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")
   };
}

然后对于listOfWords对象中的给定项目,您可以执行以下操作:

var currentWord = "cat"; // set current word key somehow, then:
console.log(listOfWords[currentWord].pic);
console.log(listOfWords[currentWord].audio);

使用 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")
    };
});
于 2012-07-26T14:21:26.000 回答
0

使用 jQuery,您可以使用.each()迭代列表项和.data()检索数据属性值。

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);
});
于 2012-07-26T14:22:41.117 回答