简体   繁体   English

JS #urls不会在第一次单击时触发该功能

[英]Js #urls doesn't trigger the function on the first click

I'd like to execute a function on a url change mysite.com/#url , for some reason when I click on a link for the first time it doesn't execute the code, 2nd and more times it works as expected , here is the code: 我想在URL更改mysite.com/#url上执行一个函数,由于某种原因,当我第一次单击链接时,它不执行代码,第二次或多次按预期工作,在这里是代码:

$(document).on('click', '.JsLink', function(event) {
    // hashUrl gets the url after the #
    var hashUrl = window.location.hash.substr(1);
   // if hashUrl is not empty should execute the function
    if (hashUrl) {getResultsByUrl(hashUrl);}
});

links : 链接:

<li class="li-menu JsLink"> <a  href="#sale" >For Sale</a> </li>
<li class="li-menu JsLink"> <a  href="#rent" >For Lease</a> </li>

there is no problems with the function coz I tried it with if (hashUrl) {alert('hello');} and it also executes only after 2nd click , Thank You 我用if (hashUrl) {alert('hello');}尝试过的函数coz没有任何问题,它也仅在第二次单击后执行,谢谢

Your event handler runs before the URL gets changed by the anchor tag. 您的事件处理程序将锚标记更改URL 之前运行。 So the first time through, you don't see any hash in the URL. 因此,从头开始,您在URL中看不到任何哈希值。 The second time through, there is a hash (from the first click). 第二次,是哈希(从第一次单击开始)。

You may want to use $(window).bind('hashchange', function (event) { ... }); 您可能要使用$(window).bind('hashchange', function (event) { ... }); instead. 代替。

This happens because the click event is fired before the URL is actually changed. 发生这种情况是因为在实际更改URL之前触发了click事件。

You should read the href property of the anchor itself: 您应该阅读锚点本身的href属性:

var hashUrl = $(this).attr("href").substr(1);

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

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