保存Cookie

时间:2017-02-12 17:01:00

标签: javascript html asp.net-mvc cookies drop-down-menu

我看到了这篇文章 - Saving dropdown menu selection in a cookie? 。我有一个下拉菜单,其中有2种语言,当我按下其中一种语言时,它会改变语言,但问题是,它总是在刷新页面后选择顶部条目。 使用链接中的代码,选择的值在页面刷新后仍保持选中状态,但现在当我按下所需的语言时,它什么都不做。该链接不再有效。

这是:

<select name="change" id="change">
<option value="en" href="@Url.Action("ChangeCulture", "Home", new { lang = "en" })">English</option>
<option value="de" href="@Url.Action("ChangeCulture", "Home", new { lang = "de" })">Deutsch</option>
</select>

带有cookie的脚本:

<script>
    function saveTheme(cookieValue) {
        var sel = document.getElementById('ThemeSelect');

        saveclass = saveclass ? saveclass : document.body.className;
        document.body.className = saveclass + ' ' + sel.value;

        setCookie('theme', cookieValue, 365);
    }

    function setCookie(cookieName, cookieValue, nDays) {
        var today = new Date();
        var expire = new Date();

        if (nDays == null || nDays == 0)
        nDays = 1;

        expire.setTime(today.getTime() + 3600000 * 24 * nDays);
        document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    document.addEventListener('DOMContentLoaded', function () {
        var themeSelect = document.getElementById('ThemeSelect');
        var selectedTheme = readCookie('theme');

        themeSelect.value = selectedTheme;
        saveclass = saveclass ? saveclass : document.body.className;
        document.body.className = saveclass + ' ' + selectedTheme;
    });
</script>

编辑:当我从此链接添加此代码时:Links in <select> dropdown options,语言会按原样更改,但现在问题是按下按钮后,选中语言不会在下拉菜单中保持可见状态。 除了脚本中的其他代码之外,这是我添加的代码:

document.getElementById('ThemeSelect').onchange = function () {
window.location.href = this.children[this.selectedIndex].getAttribute('href');
}

0 个答案:

没有答案