javascript - 如何在html頁面中修改所有外部連結形式?

來源:互聯網
上載者:User
例如,我有:http://A.com/a/index.html,該頁面裡有很多不同網站的外鏈(如b.com、c.com、d.com等)。
現在我想,用php、JS或其他方法實現,點擊外連結“b.com”,新視窗開啟的地址是“http://a.com/b/index.php?b.com”的效果。
謝謝,因不太懂代碼,希望大大們賜教,如何統一替換所有的外鏈形式?

回複內容:

例如,我有:http://A.com/a/index.html,該頁面裡有很多不同網站的外鏈(如b.com、c.com、d.com等)。
現在我想,用php、JS或其他方法實現,點擊外連結“b.com”,新視窗開啟的地址是“http://a.com/b/index.php?b.com”的效果。
謝謝,因不太懂代碼,希望大大們賜教,如何統一替換所有的外鏈形式?

捕捉 click 事件,然後在事件處理函數裡修改 href

$(document).on('click', 'a:not([data-bypass])', function(e) {    var $target = $(e.target),        href = $target.attr('href'),        prefix = 'http://a.com/b/index.php?';    if (/^http:\/\//.test(href)) {        $target.attr('href', prefix + href);    }    // 把檢查過的  標記一下,以後就不會再次做檢查    $target.attr('data-bypass', 'bypass');});

這種思路跟直接遍曆 修改 href 的思路比較,好處是絕無死角且效率高,對於後面再加入的 也依然有效。而且對於需要特殊處理的 ,只需要在標籤裡面先寫上 data-bypass 屬性就行,很方便。

jquery 擷取全部 A 標籤,然後批量替換 href 的值為 http:// 開頭的

$("a[href*='http://']").each(function() {  $(this).attr('href','http://www.fsdeveloper.net'+'/'+$(this).attr('href'));});

類似這種寫法,

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.