2014-10-09 113 views
0

有沒有辦法從JSON文件中獲得隨機值?我的JSON含有大量的基於相同的音樂藝術家的內容,所以我想更多的隨機顯示的數據,並添加一個節目之後更多按鈕...HandlebarsJS如何從JSON獲得隨機值

所以我的JSON看起來是這樣的:

[ 
    data: [{ 
    "name" : "rihanna", 
    "song" : "pour it up" 
    }, 
    { 
     "name" : "rihanna" 
     "song" : "diamonds" 
    }, 
    { 
     "name" : "ladygaga" 
     "song" : "lovegame" 
    }, 
    { 
     "name" : "ladygaga" 
     "song" : "lovegame" 
    }, 
    { 
     "name" : "ladygaga" 
     "song" : "pokerface" 
    }, 
    { 
     "name" : "ladygaga" 
     "song" : "alejandro" 
    }, 
    { 
     "name" : "fergie" 
     "song" : "fergalicious" 
    }, 
    { 
     "name" : "fergie" 
     "song" : "clumsy" 
    }, 
    etc etc 

那麼,有沒有辦法做到這一點?

回答

1

試試這個:)

var random = Math.floor(Math.random() * jsonObject.length); 
var rData = jsonObject[random]; 

附: :其中jsonObject是您的數據屬性。

0

這裏是你如何實現它。 PLUNKER

$(document).ready(function() { 

    $('button').on('click', function() { 
     getRandom(); 
     var html = template(context); 
     $('#artistlist').html(html); 
    }); 

    var source = $("#entry-template").html(); 
    var template = Handlebars.compile(source); 

    var musicArray = [{ 
     "name": "rihanna", 
     "song": "pour it up" 
    }, { 
     "name": "rihanna", 
     "song": "diamonds" 
    }, { 
     "name": "ladygaga", 
     "song": "lovegame" 
    }, { 
     "name": "ladygaga", 
     "song": "lovegame" 
    }, { 
     "name": "ladygaga", 
     "song": "pokerface" 
    }, { 
     "name": "ladygaga", 
     "song": "alejandro" 
    }, { 
     "name": "fergie", 
     "song": "fergalicious" 
    }, { 
     "name": "fergie", 
     "song": "clumsy" 
    }]; 


    var context = { 
     music: [] 
    }; 

    var musicClone = $.extend(true, [], musicArray); 

    function getRandom() { 
     var i = 2; 
     while (i-- && musicClone.length >= 1) { 
      var random = Math.floor(Math.random() * musicClone.length); 
      var data = musicClone[random]; 
      context.music.push(data); 
      musicClone.splice(random, 1); 
     } 
    } 

}); 
+0

這就是很不錯的!好吧,我必須將它添加到註冊助手中嗎?如果是這樣,我該如何獲取註冊助手中的json? – Steve 2014-10-09 10:01:59

+0

無需註冊助手。 – 2014-10-09 10:09:13