简体   繁体   English

window location href 在 jquery 内替换标签

[英]window location href inside jquery replaceWith tag

thanks for the amazing community, i'm strugling with this code i'm tring to load href link with window.location.href + string '/1/' into my jquery replaceWith tag but no luck could you help me please this is my code:感谢令人惊叹的社区,我正在努力使用此代码,我正在尝试将带有 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>');

thank you for your help again再次感谢您的帮助

Are you trying to do something like below?您是否正在尝试执行以下操作? You need to include jquery library files, and then below will work.您需要包含 jquery 库文件,然后下面将起作用。 In the code I have fixed: at the end of line 1 to;在我修复的代码中:在第 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>

Some problems with your current script...您当前脚本的一些问题...

  1. Your first line is terminated with : which causes a syntax error.您的第一行以:结尾,这会导致语法错误。 You probably meant ;您可能的意思是;
  2. To concatenate strings in JS, you use the + operator要在 JS 中连接字符串,请使用+运算符
  3. Your script appends /1/ to the end of the complete URL.您的脚本将/1/附加到完整 URL 的末尾。 If the URL contains query parameters or fragments, this will cause problems.如果 URL 包含查询参数或片段,这将导致问题。 You should manipulate the path property only您应该只操作路径属性

 // 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>

You should do this instead你应该这样做

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

And also you should ensure that you have the Jquery library included added in your code as well.您还应该确保在代码中添加了 Jquery 库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM