When changing location.hash in onclick it changes to undefined

大兔子大兔子 提交于 2020-01-05 07:43:13

问题


I have such code:

$(e).click(function() {
    console.log(this.href);
    location.hash = this.href;
});

Here e is a <li> element like this: <li href="#about">About</li>
location.hash has onchange listener:

$(window).hashchange(function() {
    if (location.hash=="") location.hash="me";
    $(".content").spin();
    $(".content").load("http://example.com/inc/"+location.hash.substr(1), function() {
        $(this).spin(false);
    });
});

UPD: Problem is not with variable accessing, because console.log prints right value of variable.


回答1:


href is not a valid attribute of LI

Add data-href (or perhaps better:data-hash) to your LI

<li data-href="somevalue">...

and use

$(e).click(function() {
    location.hash = $(this).data("href");
});


来源:https://stackoverflow.com/questions/14355639/when-changing-location-hash-in-onclick-it-changes-to-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!