如何在网址更改时触发Javascript事件

问题描述 投票:0回答:1

目前,我正在处理一个角度项目,我需要触发一个关于路由更改/ URL更改从一个页面到另一个页面的事件(因为它是一个角度项目页面不会被刷新)。

我在index.html页面中尝试过不同的场景,如下所示:

  window.onbeforeunload = function () {
   //not fit;
  });

    window.onhashchange = function () {
    //not fit;
   });

我们可以有任何其他解决方案来触发url更改事件(我不想在角度中使用侦听器)。

javascript dom-events
1个回答
0
投票

您可以通过在窗口上实现hashchange来实现此目的

如果你使用jQuery,这个plugin可能会帮助你。

或者在您的情况下检查纯JS代码

function hashHandler() {
    this.oldHash = window.location.hash;
    this.Check;

    var that = this;
    var detect = function() {
        if(that.oldHash != window.location.hash) {
            alert("HASH CHANGED - new has" + window.location.hash);
            that.oldHash = window.location.hash;
        }
    };

    this.Check = setInterval(function() { detect() }, 100);
}

var hashDetection = new hashHandler();

角度与路由器的纯演示代码示例:

import { Component, OnInit } from '@angular/core'; // I import Location so that I can query the current path
import { Location } from '@angular/common'; // I also import Router so that I can subscribe to events
import { Router } from '@angular/router'; 

@Component(
{ selector: 'app-top-nav', 
  templateUrl: './top-nav.component.html', 
  styleUrls: ['./top-nav.component.scss'] }
)
export class TopNavComponent implements OnInit { 
    route: string; 

    constructor(location: Location, router: Router) { // within our  constructor we can define our subscription
       // and then decide what to do when this event is triggered.
       // in this case I simply update my route string.
       router.events.subscribe((val) => { if(location.path() != '') { this.route = location.path(); } else { this.route = 'Home' } }); 
    } 

    ngOnInit() { 
    } 
} 

上面的代码应该可行。

© www.soinside.com 2019 - 2024. All rights reserved.