为什么这行脚本不起作用?

时间:2012-07-26 14:14:08

标签: javascript jquery

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

这是一种方式......

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

但没有这样的运气。

第二种方式是底部而不是顶部,在调用数据字时我需要数据音频和数据pic。

有人可以帮忙吗?

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>

2 个答案:

答案 0 :(得分: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")
    };
});

答案 1 :(得分: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);
});