jquery div根据url显示?

时间:2012-08-06 16:50:27

标签: javascript jquery

我有以下代码

<html>
<head>
    <script src="jquery.js"></script>
    <script>
        $(document).ready(function () {
            $("#div1").hide();
            $("#div2").hide();
        });
    </script>

</head>
<body>
    <div id="div1">This is first Div</div>
    <div id="div2">Welcome At 2nd Div </div>
</body>
</html>

网址是index.html。我怎么能显示#div1如果url就像index.html#div1和#div2如果url就像index.html#div2

1 个答案:

答案 0 :(得分:2)

$(document).ready(function){
    $("div[id^=div]").hide();
    var loc = window.location.href;
    if( loc.indexOf( '#' ) >= 0 ) {
        hash = loc.substr( loc.indexOf('#') + 1 ); // output: div1, div2 etc..
        $('#'+hash).show();
    }
});