Javascript 如何确定HashChangeEvent的原因

Javascript 如何确定HashChangeEvent的原因,javascript,Javascript,如何确定HashChangeEvent是由页面中的用户操作(单击链接、按钮等)触发的,还是由地址栏中的手动输入触发的?我认为最好的办法是创建某种包装,允许您更改window.location.hash属性,并从您想要跟踪的任何元素调用它。我已经在上创建了一个示例,以演示如何实现这一点。然而,这个例子是相当初级的。我认为这传达了你想做的事情的意义 我也会把这个例子放在这里,但它显然不起作用。如果您认为这将涵盖您的用例,请告诉我。如果需要,我可以调整它 (function($) { 'use

如何确定HashChangeEvent是由页面中的用户操作(单击链接、按钮等)触发的,还是由地址栏中的手动输入触发的?

我认为最好的办法是创建某种包装,允许您更改
window.location.hash
属性,并从您想要跟踪的任何元素调用它。我已经在上创建了一个示例,以演示如何实现这一点。然而,这个例子是相当初级的。我认为这传达了你想做的事情的意义

我也会把这个例子放在这里,但它显然不起作用。如果您认为这将涵盖您的用例,请告诉我。如果需要,我可以调整它

(function($) {

  'use strict';

  //Create a route function on the jQuery object
  //that we can use anywhere.

  /**
   * Wraps the setter for window.location.hash
   * and tracks who called it.
   * 
   * @param {Element} who The element that called route.
   * @param {string} hash The hash to set.
   */
  $.route = function(who, hash) {
    $.route.who = who;
    window.location.hash = hash;
  };

})(jQuery);
下面的代码显示了如何使用
$.route
函数跟踪哪个元素更改了
窗口.location.hash

(function($) {

  'use strict';

  window.addEventListener('hashchange', function() {
    if ($.route.who) {
      //We know this was one of our tracked elements.
      alert(`Tag Name "${$.route.who.prop('tagName')}" triggered hash change.`);
    } else {
      //We'll assume that this wasn't being tracked, and therefore
      //is most likely to be caused by user input.
      alert('We could not track what triggered "hashchange".');
    }
    //Don't forget to reset this so that if an untracked input triggered this
    //it doesn't appear that it was tracked.
    $.route.who = null;
  });

  $(function() {

    $('.hash-change').click(function(e) {
      //Do some internal routing action that can track the caller.
      var $this = $(this);
      //Get the hash to set to the URL.
      var href = $this.attr('href') || $this.data('href');
      //Use our internal routing action to track the caller.
      $.route($this, href);

      //Prevent the default action of those hyperlinks by returning false.
      return false;
    });

  });

})(jQuery);
我在示例中使用的HTML如下所示。每一个都有类散列更改。本机支持href的元素使用它,其他不使用href数据集的元素使用它

<a class="hash-change" href="home">Home</a>
<a class="hash-change" href="about">About</a>
<input type="button" class="hash-change" data-href="contact" value="Contact" />

这些元素将被跟踪,并将使用
$.route
函数更改
哈希值。任何不使用
$.route
函数的操作都不会设置$.route.who值,因此,您可以假设它是从某个源更改的,例如用户手动更改哈希


最终,您实现的任何解决方案都必须是现有功能的包装器。请看一个实时演示的示例。

根据HashChangeEvent:Yes的规范,似乎没有提供此类事件信息!我已经检查了MDN,但实际上我正在寻找一些解决方法。可能有一些方法可以解决这个问题。@RahulDesai可能会使用Function.caller,但现在根据Firefox的说法:“TypeError:‘caller’、‘callee’和‘arguments’属性可能无法在严格模式函数上访问”。