簡體   English   中英

window location href 在 jquery 內替換標簽

[英]window location href inside jquery replaceWith tag

感謝令人驚嘆的社區,我正在努力使用此代碼,我正在嘗試將帶有 window.location.href + string '/1/' 的 href 鏈接加載到我的 jquery replaceWith 標簽中,但沒有運氣能幫助我,請這是我的代碼:

var myhref=window.location.href+'/1/':
$j('.the-tag p').replaceWith('<a href="'.myhref.'">My Link</a>');

再次感謝您的幫助

您是否正在嘗試執行以下操作? 您需要包含 jquery 庫文件,然后下面將起作用。 在我修復的代碼中:在第 1 行的末尾到;

 var myhref = window.location.href + '/1/'; $('.the-tag p').replaceWith('<a href="' + myhref + '">My Link</a>');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="the-tag"> <p></p> </div>

您當前腳本的一些問題...

  1. 您的第一行以:結尾,這會導致語法錯誤。 您可能的意思是;
  2. 要在 JS 中連接字符串,請使用+運算符
  3. 您的腳本將/1/附加到完整 URL 的末尾。 如果 URL 包含查詢參數或片段,這將導致問題。 您應該只操作路徑屬性

 // Show an example with a fragment location location.hash = "#anchor" // Clone the current URL const myhref = new URL(location) // Handles cases where the current path // does or does not end in a "/" myhref.pathname = myhref.pathname.replace(/\/?$/, "/1/") $('.the-tag p').replaceWith($("<a>", { href: myhref, text: "My Link" }))
 /* This is just so you can see the href */ a::after { content: " (" attr(href) ")"; color: grey; font-size: .8rem; }
 <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script> <div class="the-tag" id="anchor"> <p></p> </div>

你應該這樣做

var myhref = window.location.href+'/1/';
$.('.the-tag p').replaceWith('<a href="'+ myhref +'">My Link</a>');

您還應該確保在代碼中添加了 Jquery 庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM