jQuery:根据URL中的#(数字符号)加载某个div

时间:2014-04-16 15:43:49

标签: javascript jquery

例如,这个网站是这样做的: https://mega.co.nz/#register

因此它会加载注册页面,因为" #register"。 我不想滚动或任何我想加载div的内容。

这是我点击链接时使用的代码。但我希望当有人直接访问mypage.com/#aboutus

时加载它
<script>
var site = location.hash;
if(site == "#about-us")
{
  $('#content').load('about.php');
}
$(document).ready(function(){
    $('.aboutus').click(function(){
        $('#content').load('about.php');
    });
})
</script>

3 个答案:

答案 0 :(得分:1)

只需使用location.hash属性:

var mysite = location.hash;
if(mysite == "#register")
{
  $("#mydiv").html("Your registration field");
}

来源:w3schools

答案 1 :(得分:1)

你几乎拥有它 - 你只需要在文档就绪处理程序中放置初始检查,以便在运行时#content存在...

<script>
    $(document).ready(function(){
        var site = location.hash;
        if (site == "#about-us") {
            $('#content').load('about.php');
        }
        $('.aboutus').click(function(){
            $('#content').load('about.php');
        });
    });
</script>

答案 2 :(得分:0)

检入javascript:

if (window.location.hash == "value1") //for #value1 fragment in the url.
{
    //load #div1 here
}
else
{
    //load #anotherDiv here
}

并在jQuery中考虑加载div(ajax,一个对话框,......)。