Javascript 如何使用jQuery根据哈希值触发不同的哈希更改函数?
我使用的是'sJavascript 如何使用jQuery根据哈希值触发不同的哈希更改函数?,javascript,jquery,hashchange,Javascript,Jquery,Hashchange,我使用的是'sjQueryhashChange事件插件。 散列部分如下所示: #x=1&y=2&z=3 var hashParameters = {}; $(window).bind("hashchange",function(event) { //if you're using the awesome hashchange plugin //$(window).hashchange(function(event) { ... var newParameters =
jQuery
hashChange
事件插件。
散列部分如下所示:
#x=1&y=2&z=3
var hashParameters = {};
$(window).bind("hashchange",function(event) {
//if you're using the awesome hashchange plugin
//$(window).hashchange(function(event) { ...
var newParameters = getParameters(event.target.location.hash.substring(1));
$.each(newParameters, function(key, value) {
if(hashParameters[key] !== value) $(window).trigger(key + "-change");
hashParameters[key] = value;
});
});
$(window).bind("andsome-change", function() {
alert("hi!");
});
function getParameters(paramString) {
//taken from http://stackoverflow.com/questions/4197591/parsing-url-hash-fragment-identifier-with-javascript/4198132#4198132
var params = {};
var e, a = /\+/g, r = /([^&;=]+)=?([^&;]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(paramString))
params[d(e[1])] = d(e[2]);
return params;
}
window.location.hash = "some=value&andsome=othervalue";
我已经有了解析它的函数getHashPart(key)
和setHashPart(key)
我希望有一个函数,只允许注册哈希的特定部分的更改。
我会这样使用它(我猜…):
如何向jQuery注册这样的函数?
是否存在类似的情况
谢谢 您可以有一个响应所有hashchange事件的函数(最好是保持hashchange插件处于使用状态),然后重定向到单独的处理程序,如下所示:
#x=1&y=2&z=3
var hashParameters = {};
$(window).bind("hashchange",function(event) {
//if you're using the awesome hashchange plugin
//$(window).hashchange(function(event) { ...
var newParameters = getParameters(event.target.location.hash.substring(1));
$.each(newParameters, function(key, value) {
if(hashParameters[key] !== value) $(window).trigger(key + "-change");
hashParameters[key] = value;
});
});
$(window).bind("andsome-change", function() {
alert("hi!");
});
function getParameters(paramString) {
//taken from http://stackoverflow.com/questions/4197591/parsing-url-hash-fragment-identifier-with-javascript/4198132#4198132
var params = {};
var e, a = /\+/g, r = /([^&;=]+)=?([^&;]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(paramString))
params[d(e[1])] = d(e[2]);
return params;
}
window.location.hash = "some=value&andsome=othervalue";
我有一个工作演示(现在使用hashchange插件,请参阅第一条注释)。说明如何为页面url设置onchange事件。但是,如果您正在做我认为您正在做的事情,那么您应该绑定设置哈希的链接以执行您希望它执行的操作,然后在文档加载时检查url中是否有哈希来执行它应该执行的操作。好文章。我会等着看其他建议的解决方案。如果我是你,我会将问题的标题改为“如何使用jQuery根据哈希值触发哈希更改上的不同函数?”。只是一个提议。+1,仅供参考,您可以在JSFIDLE中包含外部脚本-在左键单击“添加资源”并粘贴链接。或者,只需在HTML框架中粘贴
。“我不能”的意思是“我太懒了”=))非常感谢您的建议,下面是修复链接: