使用URL参数将内容放入div?

时间:2018-03-27 18:57:39

标签: javascript html if-statement url parameters

我正在选择加入页面。我希望用户的当前订阅数据显示在页面顶部。我的方法是根据URL参数将内容放入div中。如果参数不存在,我希望它放入另一个div。请参阅以下代码:

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript">
        var testSub = '<span>Subscription data</span>';
        if (/testnews=1/.test(window.location.href)) {
            document.getElementById('subscribed').innerHTML = testSub;
        } else {
            document.getElementById('not_subscribed').innerHTML = testSub;
        }
    </script>
</head>

<body>
    <div id="subscribed"></div>
    <div id="not_subscribed"></div>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

终于弄明白了。只需要将我的代码包装在一个onload功能中:

    <script type="text/javascript">
     window.onload = function(){
        var testSub = '<span>Subscription data</span>';
        if (/testnews=1/.test(window.location.href)) {
            document.getElementById('subscribed').innerHTML = testSub;
        } else {
            document.getElementById('not_subscribed').innerHTML = testSub;
        }
    }
    </script>


<body>
    <div id="subscribed"></div>
    <div id="not_subscribed"></div>
</body>

</html>