Home > Web Front-end > JS Tutorial > body text

js code to monitor url fragment changes_javascript skills

WBOY
Release: 2016-05-16 18:29:12
Original
1292 people have browsed it

Of course, it is best not to refresh the page, but if you copy the browser link, you hope to be able to locate the video you broadcast next time. The method is very simple, just change the fragment of the url.

Monitoring fragment changes is the core of this type of programming. In mainstream browsers (IE Firefox), there is an onhashchange event to monitor fragment changes.
However, there are some differences in their behavior. In IE versions before IE8, when the window.location object changes rapidly, onhashchange will not be triggered, which is a very strange bug.

The onhashchange event I wrote below has no browser differences. And a function has been added. When the page is initialized, if there is a fragment in the url, the
onhashchange event will also be triggered.

Copy code The code is as follows:

function addFragmentChangeEvent(callback)
{
var source = document.URL;
var url = source.split("#")[0];
if (window.location.hash)
{
var base_hash = " #____base____hash____";//Change the hash so that the event function is triggered when the page is initialized.
window.location = url base_hash;
}
var prevHash = window.location.hash;
window.setInterval(
function()
{
if (window. location.hash != prevHash)
{
prevHash = window.location.hash;
callback(prevHash);
}
}, 100);
if (window.location .hash)
{
window.location = source;
}
}

In fact, this technique is commonly used in js to simulate the effect of an event.
Related labels:
url
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template