2010-10-20 33 views
0

我需要更改任何本地鏈接點擊時的href。 我已經研究出如何選擇正確的鏈接並創建新的url,但不知道如何更改位置。我需要確定任何其他點擊事件也已經運行,所以我不能立即改變位置。如何使用javascript/jquery更改點擊時任何本地鏈接的目標?

var my_host = 'example.com'; 
$(document).click(function(e) { 
    if(e.target.hostname == my_host) 
    { 
     alert(e.target.protocol + "//" + e.target.hostname + "/#" + e.target.pathname + e.target.search); 
     //... 
    } 
}); 

這與我的earlier question有關。

回答

3

可以綁定在你的本地鏈接這樣的事件並使用attr方法來改變href

$('a[href*="yourdomain.com"]').click(function(){ 
    // your code before changing href 
    $(this).attr('href', 'new url here'); 
}); 

用自己的域名替換yourdomain.com所以,上面的代碼只針對本地鏈接。

+0

謝謝。你已經回答了我的問題,並縮短了代碼。但是,你也引入了一個bug。如果域名在路徑中的其他位置,例如作爲查詢字符串中的返回URL,則會被錯誤觸發。 – SystemicPlural 2010-10-20 08:34:17

+0

@SystemicPlural:你可以使用'document.location.search'找出url的東西,並相應地提取部分。 – Sarfraz 2010-10-20 08:44:25

0

這是完全未經測試,但應該讓你你要去的地方:

var site = "http://yourdomain.com"; 

// Match anchor tags with an href value that starts with your 
// site URL, or that start with/which are relative URLs (also 
// your site). 
$('a[href^="' + site + '"] a[href^="/"]').click(function(){ 
    var url = $(this).attr('href'); 
    if (url.indexOf(site) != -1) { 
     url = site + "/#" + url.replace(site, ""); // Quick dirty way to get the path component of the URL 
    } else { 
     url = "/#" + url; 
    } 
    $(this).attr("href", url); 
}); 

請注意,我看了你的其他問題,我個人不明白你爲什麼會做這個click事件,而不是在頁面加載後立即替換所有的href值。

+0

這不適用於https鏈接。做onclick的原因是,替換一個鏈接比幾十個要少得多。另外,就我而言,內容是動態加載的 - 所以一個解決方案是理想的。 – SystemicPlural 2010-10-20 08:38:17

+0

以前的答案1)沒有工作,2)沒有考慮到相關的URL。您可以在我的代碼中添加幾個字符來處理https哈哈哈 – mellowsoon 2010-10-20 08:49:43

+0

P.S.不知道你在做什麼,但如果你想要搜索引擎蜘蛛索引正確的URL,你會想要更改所有的URL(而不僅僅是點擊的URL)。 – mellowsoon 2010-10-20 08:51:57

0

感謝Sarfraz:這裏是沒有錯誤的答案。

var my_host = "example.com"; 
$('a[href^="/"], a[href^="http://' + my_host + '"], a[href^="https://' + my_host + '"]').click(function(e){ 
    $(this).attr('href', e.target.protocol + "//" + e.target.hostname + "/#" + e.target.pathname + e.target.search); 
}); 
相關問題