简体   繁体   中英

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:

$(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

Your event handler runs before the URL gets changed by the anchor tag. So the first time through, you don't see any hash in the URL. The second time through, there is a hash (from the first click).

You may want to use $(window).bind('hashchange', function (event) { ... }); instead.

This happens because the click event is fired before the URL is actually changed.

You should read the href property of the anchor itself:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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