简体   繁体   English

Javascript / jQuery哈希URL无法执行

[英]Javascript/jQuery hash URL doesn't execute

I have a hash URL that doesn't execute the javascript/jQuery unless I manually hit the enter key or refresh the page. 我有一个hash URL ,除非我手动按Enter键或刷新页面,否则该hash URL不执行javascript/jQuery

$(function($){
  var key=$(location).attr('hash');

  if (key){
    $('#div').find('div.div2').load('sig.php?k='+key)
  }
});

This works fine when I type in the URL manually or refresh the page but whenever I use <a href="url#SecReTkEy"> or Javascript/jQuery functions such as: 当我手动输入URL或刷新页面,但是每当我使用<a href="url#SecReTkEy">Javascript/jQuery函数(例如:

$(location).attr('href','url#SecReTkEy');

$('a').prop('href','url#SecReTkEy');

window.location.replace('url#SecReTkEy');

window.location.href('url#SecReTkEy');

Can any one tell me why and how to fix this? 谁能告诉我为什么以及如何解决这个问题? ` `

你应该使用

location.href = #whatever

You don't need JQuery in order to retrieve the hash. 您不需要JQuery即可检索哈希。 Use the fully qualified reference to window.location.hash (I'm guessing location didn't work as you already have a var named location ). 使用对window.location.hash的完全限定的引用(我猜location无效,因为您已经有一个名为location )。

Also, don't forget to URL encode the key using encodeURIComponent . 另外,不要忘记使用encodeURIComponent对密钥进行URL编码。 Additionally the $ is not needed if you want to execute this on document ready . 另外, 如果要在准备好的文档上执行此操作,则不需要$

$(function(){
  var key = window.location.hash;

  if (key){
    $('#div').find('div.div2').load('sig.php?k=' + encodeURIComponent(key))
  }
});

I have a hash URL that doesn't execute the javascript/jQuery unless I manually hit the enter key or refresh the page.

这是因为它仅启动一次,而不是在eventBinder上具有hashchange

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM