我有一个 Backbone Collection,我想从每个模型中获取特定值,然后将该值插入到 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 失败。我做错了什么?
最佳答案
试试这个
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
。
关于javascript - BackboneJs如何循环遍历集合从每个模型中获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28560409/