window location href inside jquery replaceWith 标签

window location href inside jquery replaceWith tag

感谢这个了不起的社区,我正在为这段代码而苦苦挣扎,我想用 window.location.href + 字符串 '/1/' 将 href link 加载到我的 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>

你应该这样做

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

此外,您还应确保在代码中也添加了 Jquery 库。

您当前的脚本存在一些问题...

  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>