如何将jquery函数/回调转换为文档准备好

时间:2012-02-20 10:40:04

标签: javascript jquery

如何更改此代码以便我可以将其添加到准备好jquery的标准文档中,以便我的所有脚本都在一起。

 /*
 * Fetch RSS feed once page has finished loading.
 */
(function(url, callback) {
    jQuery.ajax({
        url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
        dataType: 'json',
        success: function(data) {
            callback(data.responseData.feed);
        }
    });
})('http://www.bet365.com/news/en/betting/sports/rss', function(feed){
    var entries = feed.entries, content, publishDate;
    for (var i = 0; i < entries.length; i++) {
        publishDate = new Date(entries[i].publishedDate);
        date = publishDate.getDate() + '/' + publishDate.getMonth() + '/' + publishDate.getFullYear();
        content = truncateText((entries[i].contentSnippet) ? entries[i].contentSnippet : entries[i].content, 100);
        jQuery('#rss > ul').append('<li><a href="' + entries[i].link + '" title=" ' + content + ' " target="_blank"><span> ' + date + '</span>' + entries[i].title + '</a></li>');
    }
});

2 个答案:

答案 0 :(得分:2)

将功能分开..使用和理解很好

var my_callback = function(feed){ // Change to desired URL
    var entries = feed.entries, content, publishDate;
    for (var i = 0; i < entries.length; i++) {
        publishDate = new Date(entries[i].publishedDate);
        date = publishDate.getDate() + '/' + publishDate.getMonth() + '/' + publishDate.getFullYear();
        content = truncateText((entries[i].contentSnippet) ? entries[i].contentSnippet : entries[i].content, 100);
        jQuery('#rss > ul').append('<li><a href="' + entries[i].link + '" title=" ' + content + ' " target="_blank"><span> ' + date + '</span>' + entries[i].title + '</a></li>');
    }

function make_ajax_call(url, callback) {
    jQuery.ajax({
        url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
        dataType: 'json',
        success: function(data) {
            callback(data.responseData.feed);
        }
    });
}

然后

$(document).ready(function(){
  make_ajax_call('http://www.bet365.com/news/en/betting/sports/rss',my_callback);
});

答案 1 :(得分:0)

用它包装:

$(function(){
  // Your code here
});

实际上$$.ready的别名(与$(document).ready相同)如果函数作为参数传递