我正在尝试使用 jQuery 来响应 # 之后 url 中的更改。我进行了一些搜索,但我认为我没有使用正确的搜索词。
明确地说,我希望能够像这样提供指向页面的外部链接:
<a href="example.com/foo/#home">home</a>
并包含内部链接以动态更改页面上的内容:
<a href="#site-index">site index</a>
Gmail 可以做到这一点。例如,我可以将您直接链接到您的发件箱:https://mail.google.com/mail/u/0/#sent
谢谢。
最佳答案
这是您要找的吗:
(function(){
anchor = document.location.hash, handlers = [];
jQuery.extend({
anchorHandler: {
add: function(regexp, callback) {
if (typeof(regexp) == 'object') {
jQuery.map(regexp, function(arg){
args = {r: arg[0], cb: arg[1]};});}
else args = {r: regexp, cb: callback};
handlers.push(args);
return jQuery.anchorHandler;
}
}
})(document).ready(function(){
jQuery.map(handlers, function(handler){
match = anchor.match(handler.r) && anchor.match(handler.r)[0] || false;
if (match) handler.cb.apply(this, [match, (anchor || false)]);});});
})();
像这样添加触发器:
$.anchorHandler
.add(/\#ch\-cheatsheet/, h.comment.showCheatsheet)
.add(/\#comment\-compose/, h.comment.showCompose)
.add(/\#comment\-\d+/, h.comment.focus);
关于Javascript 响应 url # 部分的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3981090/