You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery为URL末尾添加#respond失效问题的解决方法

问题:修改jQuery代码添加#respond到URL末尾失效的解决办法

问题背景

你原本的这段jQuery代码可以正常运行:

$('a.comment-reply-link').each(function(){ 
    this.href = this.href.replace("dummy_comment", "author"); 
    this.href = this.href.replace("#comment-", "?replytocom="); 
});

但当你尝试在URL末尾添加#respond时,修改后的代码却无法正常工作:

$('a.comment-reply-link').each(function(){ 
    this.href = this.href.replace("dummy_comment", "author"); 
    this.href = this.href.replace("#comment-", "?replytocom="); 
    this.href + '#respond'; 
});

问题原因与解决办法

哦,我一眼就看出问题所在啦!你最后一行的this.href + '#respond';只是完成了字符串拼接操作,但没有把拼接后的结果重新赋值给this.href。JavaScript里这种操作不会自动更新原变量,必须明确进行赋值才行。

只需要把最后一行改成赋值语句,问题就解决了:

$('a.comment-reply-link').each(function(){ 
    this.href = this.href.replace("dummy_comment", "author"); 
    this.href = this.href.replace("#comment-", "?replytocom="); 
    this.href += '#respond'; 
    // 也可以写成 this.href = this.href + '#respond'; 两种写法效果完全一致
});

这样就能把拼接后的完整URL重新赋值给链接的href属性,完美实现你想要的在URL末尾添加#respond的需求啦!

如果你想让代码更简洁,还可以把三次操作链式调用合并成一行,可读性也很不错:

$('a.comment-reply-link').each(function(){ 
    this.href = this.href.replace("dummy_comment", "author")
                         .replace("#comment-", "?replytocom=")
                         + '#respond'; 
});

内容的提问来源于stack exchange,提问作者Maanstraat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 06:02:33