在位置更改上重写URL
问题描述:
我正在寻找一种方式来在用户想要更改页面时重写位置的URL。所以,让我们说,你有这样的事情:在位置更改上重写URL
<body>
<a href="http://example.com" />
</body>
有没有一种方法可以让我赶上URL变化的时刻,位置改变之前实际修改URL,比如我想HREF变成像相对链接\http://example.com
和实际在那里重定向页面。
答
如果你只是想陷阱的链接,然后修改它,然后是的,这很简单...
$("a").on("click", function(e) {
e.preventDefault(); // stops the link doing its default thing
window.location.href = "something/" + $(this).attr("href");
});
你显然需要修改的位置发生变化的线条,使得它修改HREF价值,但你需要。我还建议给链接一个类并选择它们,因为上面的代码会影响页面上的每个链接。
最后,这将需要在DOM加载后运行,因此要么将它包装在您选择的document.ready
处理程序中,要么将其放在主体底部的脚本中。
答
您可以从这里工作。此外,您需要在htaccess中使用urlrewrite才能正常工作。
$(function() {
$('.buttonn').on('click', function (e) {
var seperator = (window.location.href.indexOf("?") === -1) ? "?" : "&";
if (window.location.href.indexOf("s1") === -1 && window.location.href.indexOf("s2") != -1) {
window.location.href = window.location.href.replace(/&?s2=([^&]$|[^&]*)/i, "&s1=s1");
} else if (window.location.href.indexOf("s1") != -1) {
window.location.href = window.location.href.replace(/&?s1=([^&]$|[^&]*)/i, "&s1=s1");
} else {
window.location.href = window.location.href + seperator + "s1=s1";
}
});
});
$(function() {
$('.buttono').on('click', function (e) {
var seperator = (window.location.href.indexOf("?") === -1) ? "?" : "&";
if (window.location.href.indexOf("s2") === -1 && window.location.href.indexOf("s1") != -1) {
window.location.href = window.location.href.replace(/&?s1=([^&]$|[^&]*)/i, "&s2=s2");
} else if (window.location.href.indexOf("s2") != -1) {
window.location.href = window.location.href.replace(/&?s2=([^&]$|[^&]*)/i, "&s2=s2");
} else {
window.location.href = window.location.href + seperator + "s2=s2";
}
});
});
对不起,我不清楚。我实际上需要检测document.location何时发生更改,其中不仅包括元素,还包括手动javascript。 onbeforeunload事件处理程序将检测位置变化,但我不知道如何获取它应该去的URL,你有什么想法吗? – Zed 2014-11-06 12:02:25
在这种情况下,没有。我不知道有什么方法(使用Javascript)每次都没有确认框改变目标URL(使用onbeforeunload)。 – Archer 2014-11-06 12:10:53
似乎无法完成。无论如何,谢谢你,这段代码也会帮助我。 – Zed 2014-11-06 12:12:23