繁体   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