我有一个未执行的回调函数。我怀疑它被当作字符串,但是我不确定。
代码如下。
另外,这是一个简化的jsFiddle,具有更多详细信息:http://jsfiddle.net/oakley808/sH5XE/3/

基本上,它只是使用对象的设置来迭代for循环。最后一行config.feeds[i].cb是失败的。有任何想法吗?

// the callback function
function rssdone(){
    $('#cbBlock').append('did some callback stuff<br>');
}

// the settings for the loop below
var config = {
  "feeds": [
    {
        "container": "#block1",
        "url":"http://apps1.eere.energy.gov/news/rss/program.cfm?topic=1010",
        "limit":"4",
        "layoutTemplate": "<ol type='1'>{entries}</ol>",
        "entryTemplate": "<li>{title}</li>",
        "cb":"rssdone"
    },
    {
        "container": "#block2",
        "url":"http://apps1.eere.energy.gov/news/rss/financial_opps_solar.cfm",
        "limit":"2",
        "layoutTemplate": "<ol type='A'>{entries}</ol>",
        "entryTemplate": "<li>{title}</li>",
        "cb":"rssdone"
    }
  ]
}

// the logic
for( var i=0; i < config.feeds.length; i+=1 ) {
  $( config.feeds[i].container ).rss(
    config.feeds[i].url,
    {
        limit:          config.feeds[i].limit,
        layoutTemplate: config.feeds[i].layoutTemplate,
        entryTemplate:  config.feeds[i].entryTemplate
    },
    // this fails to use the callback for some reason
    config.feeds[i].cb

    // use this instead and it works!
    // rssdone
  );

}

最佳答案

是的,您将配置对象存储为json而不是js对象。引号将其视为字符串。从“ rssdone”引用周围删除引号,它应该起作用:

var config = {
  "feeds": [
    {
        "container": "#block1",
        "url":"http://apps1.eere.energy.gov/news/rss/program.cfm?topic=1010",
        "limit":"4",
        "layoutTemplate": "<ol type='1'>{entries}</ol>",
        "entryTemplate": "<li>{title}</li>",
        "cb":rssdone
    },
    {
        "container": "#block2",
        "url":"http://apps1.eere.energy.gov/news/rss/financial_opps_solar.cfm",
        "limit":"2",
        "layoutTemplate": "<ol type='A'>{entries}</ol>",
        "entryTemplate": "<li>{title}</li>",
        "cb":rssdone
    }
  ]
}

关于javascript - JavaScript回调函数未执行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16429969/

10-09 15:25