jQuery动态选择器返回undefined

时间:2014-04-14 14:44:29

标签: javascript jquery

我确信我忽略了某些事情,但这让我感到困惑。

启动html:

<div id="col-header-1"> ... </div>

使用Instafeed(js插件)获取instagram图像 - 工作正常。正确输出以下内容(在col-header-1中):

<div class="instagram-headers" data-highres="http://origincache-frc.fbcdn.net/10175356_1376290249321406_570358524_s.jpg"></div>

这不起作用,url返回undefined:

function replaceCssBackgroundWithImage(target){
  var url = $('#' + target + ' > .instagram-headers').attr('data-highres');
  $('#' + target).css('background-image','url(' + url + ')');
}

结果

<div style="background-image: url('undefined');" id="col-header-1">

所以它正确定位。

单步执行(firefox's)控制台会产生正确的结果:

target = 'col-header-1' //=>"col-header-1"

var url = $('#' + target + ' > .instagram-headers').attr('data-highres'); //=> undefined

url //=> "http://origincache-frc.fbcdn.net/10175356_1376290249321406_570358524_s.jpg"

$('#' + target).css('background-image','url(' + url + ')'); //=> [object Object]

结果

<div style="background-image: url("http://origincache-frc.fbcdn.net/10175356_1376290249321406_570358524_s.jpg");" id="col-header-1">

我不知所措,感谢任何帮助,

谢谢!

更新:Instafeed构造函数

function getMultipleFeeds(targets){
var feeds = [];
var opts = {};
for (var i=0,len=targets.length;i<len;i++){
if (targets[i].match('header')){
    opts = {
        tagName: "TAG",
        target: targets[i],
        limit: '1',
        get: 'tagged',
        user:'USER',
        clientId:'CLIENTID',
        template:'<div class="instagram-headers" data-highres="{{image}}"></div>',
        useHttp:true,
        before: replaceCssBackgroundWithImage(targets[i]),
    };
...
feeds.push(new Instafeed(opts));
  }
return feeds;
}

var myFeeds = getMultipleFeeds(['col-header-1','col-header-2','col-header-3','instafeed','banner']);

for(var i=0, len=myFeeds.length; i < len; i++) {
  myFeeds[i].run();
}

1 个答案:

答案 0 :(得分:1)

通过查看不安全的文档,您可能希望在replaceCssBackgroundWithImagemethod回调中调用after,而不是before回调。尝试改变之前和之后:

function getMultipleFeeds(targets){
var feeds = [];
var opts = {};
for (var i=0,len=targets.length;i<len;i++){
if (targets[i].match('header')){
opts = {
    tagName: "TAG",
    target: targets[i],
    limit: '1',
    get: 'tagged',
    user:'USER',
    clientId:'CLIENTID',
    template:'<div class="instagram-headers" data-highres="{{image}}"></div>',
    useHttp:true,
    after: replaceCssBackgroundWithImage(targets[i]),
};
...
feeds.push(new Instafeed(opts));
  }
return feeds;
}

var myFeeds = getMultipleFeeds(['col-header-1','col-header-2','col-header-3','instafeed','banner']);

for(var i=0, len=myFeeds.length; i < len; i++) {
  myFeeds[i].run();
}

原因是您尝试定位的元素在您尝试访问它时未被添加到DOM中,因此返回undefined。