根据if语句显示div

use*_*100 3 javascript

我正在尝试使用此代码隐藏或显示基于 url 参数“方向”的 div 我无法让它工作,想知道是否有更好的方法。示例网址 = http://domain.com?direction=south&season=summer - 谢谢

<head>
<script type="text/javascript">

        function getUrlVars()
        {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for(var i = 0; i < hashes.length; i++)
            {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

        var myVal = getUrlVars()["direction"];


        if(myVal == "north") {

            document.getElementById('north').style.display = 'block'; 
        }else {

            document.getElementById('south').style.display = 'none'; 

        }
        </script>
        </head>

        <body>

        <div id="north">Some text</div>

        <div id="south">Some text</div>

        </body>
Run Code Online (Sandbox Code Playgroud)

ipr*_*101 5

您缺少一个$(document).ready(如果您使用 jQuery)或window.onload块 -

$(document).ready(function() {
    var myVal = getUrlVars()["direction"];

    if(myVal == "north") {
        document.getElementById('north').style.display = 'block'; 
    }else {
        document.getElementById('south').style.display = 'none'; 
    }
});
Run Code Online (Sandbox Code Playgroud)

或没有 jQuery -

window.onload = function() {
        var myVal = getUrlVars()["direction"];

        if(myVal == "north") {
            document.getElementById('north').style.display = 'block'; 
        }else {
            document.getElementById('south').style.display = 'none'; 
        }
}
Run Code Online (Sandbox Code Playgroud)

当您尝试显示/隐藏它们时,您的代码可能无法正常工作,因为 div 尚未加载到 DOM 中。

示例:http : //jsfiddle.net/manseuk/RTrgN/1/