检测 url 变化的特定部分

Detect specific part of url change

我在检测 url 上的变化时遇到问题,问题是,我在 # 之后使用 url 的相同第一部分,例如

mySite.com/masterPage.html#pageView=employee&employeeCode=10

如果我用 window.onhashchange = function(); 监听变化,如果我只是将 url 更改为

,它不会检测到更改
 mySite.com/masterPage.html#pageView=student

因为散列和以前一样,关于如何检测 pageView 在 url 变化

上的变化的任何想法

用 jQuery 做,对我来说效果很好。

$(window).on("hashchange", function(){
    alert('change');
});

测试蒙山 mySite.fr/#toto 和 mySite.fr/#tototata 锚点更改时触发事件。

如果您使用 link 更改 URL 哈希,则使用 onhashchange 没有问题,因为有一个操作可以更改它(锚点或脚本)。 看看这个:https://jsfiddle.net/FrancescoRombecchi/jxbq7epg/1/

<body onhashchange="myFunction()">

<p>Click the button to change the anchor part of the current URL to #part5</p>

<button onclick="changePart()">Try it</button>
<a href="#prova">Go to hello</a>
<hr>
<p id="demo"></p>

<p id="hello">hello<p>

<script>

function changePart() {
    location.hash = "part5";
    var x = location.hash;
    document.getElementById("demo").innerHTML = "The anchor part is now: " + x;
}

// Alert some text if there has been changes to the anchor part
function myFunction() {
    alert("The anchor part has changed!");
}


</script>

</body>

但是,如果直接数字 url 则没有可以引发事件的操作,因此无法使用 onshashchange 函数。而是使用 cookie 来保存最后的哈希并检查它是否已更改。

再见