【问题标题】:BackboneJs how to loop through collection get specific value from each modelBackboneJs 如何循环通过集合从每个模型中获取特定值
【发布时间】:2015-02-17 10:59:32
【问题描述】:

我有一个主干集合,我想从每个模型中获取特定值,然后将该值插入到 Iframe 中。

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

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

和我的主干代码:

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 失败。我做错了什么?

【问题讨论】:

    标签: javascript backbone.js iframe


    【解决方案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。

    【讨论】:

    • @Steve 我已经更新了示例。据我了解,您的 this.collection 和 $('iframe.playlist') 的长度相同。如果集合中有 5 个页面中的项目也有 5 个 iframe... 是否正确?
    • @Steve 如您所见,我添加了新示例
    • 这太完美了!谢谢! :-)
    • 现在我们开始了,我发现在某些情况下我需要使用lastIndexOf(':')+1 - 我怎样才能以最好的方式包含此检查?
    • 嗯,它仍然没有得到lastIndexOf(':')+1 :-s - 我喜欢这种方法......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多