如何确定HashChangeEvent是否由页面中的用户操作触发(单击链接,按钮等),或者在地址栏中手动输入?
答案 0 :(得分:0)
我认为您最好的选择是创建某种包装器,允许您更改window.location.hash
属性,并从您想要跟踪的任何元素中调用它。我在Plunker上创建了一个示例,以展示我对如何做到这一点的想法。然而,这个例子非常简陋。我认为它传达了你尝试做的事情。
我也将这个例子放在这里,但它显然不起作用。如果您认为这将涵盖您的用例,请告诉我。如果需要,我可以调整它。
(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
函数来跟踪哪个元素更改了window.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
函数更改hash
值。任何不使用$.route
函数的东西都不会设置$ .route.who值,因此,您可以假设它已从某些来源更改,例如用户手动更改散列。
最终,您实施的任何解决方案都必须是现有功能的包装器。请查看Plunker示例进行现场演示。