BackboneJs如何遍历集合从每个模型中获取特定值

时间:2015-02-17 10:59:33

标签: javascript backbone.js iframe

我有一个Backbone Collection,我希望从每个模型中获取一个特定值,然后将该值插入到iframe中。

所以,我有多个Iframe,我想动态插入data-src,iframe的基本代码是:

<iframe class="playlist" data-src=""></iframe>

和我的Backbone代码:

this.collection.each(function(spotify) {
    var service = spotify.get('services').spotify;
    var spotifyplayId = service.substr(service.lastIndexOf('/') +1);
    console.log(spotifyplayId)
    $('iframe.playlist').each(function(spotifyplayId) {
        $(this).attr('data-src', 'https://embed.spotify.com/?uri=spotify:user:digster.dk:playlist:'+ spotifyplayId);
    });
});

console.log(spotifyplayId)为我提供了正确的数据,只有动态插入到iframe中失败。我做错了什么?

1 个答案:

答案 0 :(得分:1)

试试这个

this.collection.each(function(spotify, index) {
    var service       = spotify.get('services').spotify,
        spotifyplayId = service.substr(service.lastIndexOf('/') +1);

    $('iframe.playlist').eq(index).attr('data-src', 'https://embed.spotify.com/?uri=spotify:user:digster.dk:playlist:' + spotifyplayId);
});

因为在您的示例中spotifyplayId是循环中的索引(0,1,2),但您需要从父作用域获取spotifyplayId。在我们的案例中,最好使用.eq代替$.each