如何解决jquery replaceWith 标签内的窗口位置href
感谢出色的社区,我正在努力处理这段代码 这是我的代码:
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>
您当前脚本的一些问题...
- 您的第一行以
:
结尾,这会导致语法错误。你可能是说;
- 要在 JS 中连接字符串,请使用
+
运算符 - 您的脚本将
/1/
附加到完整 URL 的末尾。如果 URL 包含查询参数或片段,这将导致问题。您应该只操作 path 属性
// 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 库。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。