-3

我正在使用 jQuery 更改document.readyhref中的<a>标记。我要替换标签的 URL 具有编码字符。当我第一次加载页面但页面刷新 (F5) 后链接工作正常。

我的代码(在 document.ready 中)

var url = "/news#Default=%7B%22k%22%3A%22%22%7D"
$("[href$=newsRD]").attr("href", url);

当我刷新页面时,javascript中的URL保持不变,但它<a>通过将所有更改替换%%25结果是链接不再有效。它给出了这个:

/news#Default%257B%2522k%2522%253A%2522%2522%257D

有没有办法解决这个问题?

谢谢!

4

1 回答 1

2

问题是您对 url 进行了两次编码。您会注意到,如果您在控制台中运行以下命令:

encodeURI("/news#Default=%7B%22k%22%3A%22%22%7D")
// will print your second result => "/news#Default=%257B%2522k%2522%253A%2522%2522%257D"

在对其进行编码之前,请运行 decode 函数以确保您没有对已编码的 url 进行编码。看看这些资源:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

于 2018-06-08T15:42:15.107 回答