如何使用 jQuery 更改超連結的 href 屬性?


jQuery attr() 方法用於更改超連結的 href 屬性。查詢 attr() 方法用於獲取匹配的 HTML 元素的任何標準屬性的值。我們來看一個例子。

首先,獲取當前 URL −

var httpUrl = $(this).attr("href"); 

使用上面看到的 replace() 替換上述內容來建立一個新 URL −

var httpsUrl = httpUrl.replace("http://", "https://");

我們將使用我們上面看到的內容將 https 連結轉換為連結 −

<p><a href="https://tutorialspoint.tw">Tutorialspoint</a></p> <p><a href="https://tutorialspoint.tw/market/index.asp">Tutorialspoint Courses</a></p> <p><a href="https://tutorialspoint.tw/latest/ebooks">Tutorialspoint EBooks</a></p> <p><a href="https://tutorialspoint.tw/questions/index.php">Tutorialspoint QA</a></p>

示例

讓我們看一個完整的示例來更改超連結的 href 屬性 −

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery Example</title> <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script> <script> $(document).ready(function(){ $('a[href^="http://"]').each(function(){ var httpUrl = $(this).attr("href"); // Get current url var httpsUrl = httpUrl.replace("http://", "https://"); // Create new url $(this).attr("href", httpsUrl); }); }); </script> </head> <body> <h1>Old to New URL</h1> <p>We have converted http to https below:</p> <p><a href="https://tutorialspoint.tw">Tutorialspoint</a></p> <p><a href="https://tutorialspoint.tw/market/index.asp">Tutorialspoint Courses</a></p> <p><a href="https://tutorialspoint.tw/latest/ebooks">Tutorialspoint EBooks</a></p> <p><a href="https://tutorialspoint.tw/questions/index.php">Tutorialspoint QA</a></p> </body> </html>

輸出

更新於:2022 年 11 月 1 日

3K+ 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告