如何使用 jQuery 更改超链接的 href 属性?

htmlweb developmentfront end technology更新于 2024/6/18 22:36:17

jQuery attr() 方法用于更改超链接的 href 属性。Query attr() 方法用于从匹配的 HTML 元素中获取任何标准属性的值。让我们看一个例子。

首先,获取当前 URL −

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

使用 replace() 替换上述 URL 来创建新 URL −

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

我们将使用上面看到的方法将 https 链接转换为 link −

<p><a href="http://www.tutorialspoint.com">Tutorialspoint</a></p> <p><a href="http://www.tutorialspoint.com/market/index.asp">Tutorialspoint Courses</a></p> <p><a href="http://www.tutorialspoint.com/latest/ebooks">Tutorialspoint EBooks</a></p> <p><a href="http://www.tutorialspoint.com/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="http://www.tutorialspoint.com">Tutorialspoint</a></p> <p><a href="http://www.tutorialspoint.com/market/index.asp">Tutorialspoint Courses</a></p> <p><a href="http://www.tutorialspoint.com/latest/ebooks">Tutorialspoint EBooks</a></p> <p><a href="http://www.tutorialspoint.com/questions/index.php">Tutorialspoint QA</a></p> </body> </html>

输出


相关文章


有用资源