2012-02-20 34 views
0

如何更改此代碼,以便將其添加到準備好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>'); 
    } 
}); 
+0

$(function(){/ *以上代碼都在這裏* /}); – 2012-02-20 10:44:10

+0

沒有什麼能阻止你將這段代碼添加到你的.ready代碼中。你能把它放在那裏來更具體地說明你想要做什麼嗎?也許我錯過了一些東西。 – sngregory 2012-02-20 10:49:22

回答

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); 
     } 
    }); 
} 

then

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

這種分離還會污染全球名稱空間,但某些功能可能不太好。當然,在很多情況下,它可能會變得很厲害...... – 2012-02-20 10:46:51

+0

非常好,謝謝你分享保存一個函數加載數據的洞察力,以及另一個功能來完成數據的所有操作。謝謝。 – blackhawk 2013-08-16 21:56:15

0

只把它包:

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

其實$$.ready一個別名(和它的同$(document).ready)如果函數作爲參數傳遞