2012-01-13 23 views
2

根據引薦來源網址加載特定內容ID這裏是我的代碼示例,當用戶click有鏈接時,它將加載特定內容id,並且如果有no click動作將顯示default內容爲#content div如何使用.load()

$(document).ready(function() { 
    $.ajaxSetup({ 
     cache: false 
    }); 
    $("a.view").live('click', function (e) { 
     var id = $(this).data("id"); 
     $('#content').load("content.php?" + id); 
     e.preventDefault(); 
    }); 
    $('#content').load("content.php"); 
}); 

問題,如何將用戶使用direct link時自動加載內容或鍵入URL欄中:例如http://domain.com/content.php?id=5

所以,如果用戶類型或使用直接鏈接我想劇本究竟做這樣.live('click')並加載current id示例爲5

讓我知道。

+1

以下是如何使用JavaScript獲取'GET'參數:http://stackoverflow.com/questions/1403888/get-url -parameter-WI th-jquery - 你可以檢查他們的負載,如果他們被設置,然後決定做什麼。也許你可以將點擊函數外包給一個帶有一個參數的命名函數,然後在設置GET參數或點擊時調用它。 – Quasdunk 2012-01-13 13:25:18

+0

你試過在你的查詢字符串中命名id參數嗎? '$('#content')。load(「content.php?id =」+ id);' – jrummell 2012-01-13 13:28:42

回答

2

使用你的榜樣,你需要一個錨綁定到:

<a href="#" data-id="5" class="view">Some Link</a> 

然後代碼應該工作如下:

$(function(){ 
    // bind to current and future anchors with the "view" class applied 
    $('a.view').live('click',function(){ 
    // grab the content and load it in to the container 
    $('#container').load('content.php?id=' + $(this).data('id')); 
    // return false so it doesn't follow the link 
    return false; 
    }); 

    // also load the default content (before any click event) 
    $('#container').load('defaultContent.php'); 
}); 

不過,如果你正在尋找一個無縫(和搜索引擎優化可接受)的內容頁面,我會着眼於使用hashbang語法:What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?