javascript - 复选框控件不接受页面加载值

标签 javascript jquery asp.net cookies checkbox

我的 _Layout.cshtml 上有以下 JS。基本上,在每个“页面加载”中,复选框都会设置为 Checked(true),即使代码应将其设置为 Cookie。
如果我只是在页面加载时将其设置为 false,它就可以工作。(例如 $("#ShowInactive").prop("checked", false); )但是,正如您在代码中看到的,我可以根据 Cookie 在 Click 事件中设置复选框的值。

我也尝试过将函数设置为 $(document).ready(function () {但注意到不同。

<script type="text/javascript">
    $(function () {
        console.log('1 - ' + Cookies.get('ShouldShowInactive'));
        var Inactive = Cookies.get('ShouldShowInactive') == true ? true : false;
        $("#ShowInactive").prop("checked", Inactive);

        $("#ShowInactive").click(function () {
            console.log('2 - ' + Cookies.get('ShouldShowInactive'));
            var ShowInactive = this.checked ? true : false;
            console.log('3 - ' + ShowInactive);
            Cookies.set('ShouldShowInactive', ShowInactive);
            console.log('4 - ' + Cookies.get('ShouldShowInactive'));
        });
    });
</script>

复选框控件:

<div class="pull-right checkbox">
   <label class="btn btn-success">
       @(Html.Kendo().CheckBox().Name("ShowInactive").Label("Show Inactive"))
   </label>
</div>

当我检查 cookie 时,通过我的 Console.log()通过 Chrome 开发工具,该值始终显示为 truefalse 。另外,在上述方式之前我试图将其直接设置为 Cookies.get('ShouldShowInactive')基本上,这是在页面加载时始终选中复选框的一种方式,而当前方式始终未选中该复选框。这两种方式都会忽略 Cookie 的正确值。

最佳答案

Cookies.get() 函数返回一个字符串,"true"== true 将计算为 false。将条件更改为

 var Inactive = Cookies.get('ShouldShowInactive') == "true" ? true : false;

关于javascript - 复选框控件不接受页面加载值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37185530/

相关文章:

javascript - jQuery DataTable 分页刷新

asp.net - 为什么我的 Azure 虚拟机未显示在 ASP.NET MVC 应用程序的 Visual Studio 发布功能中?

javascript - 更改前置文件输入的位置

javascript - 在没有用户交互的情况下关闭选项卡时提示消息?

javascript - 匹配带有前导或尾随星号的行的正则表达式

javascript - iOS 上 jQuery.each() 和 Underscore.each() 的神秘失败

jquery - 使用 jQuery 更改背景图像的值

javascript - 如何访问 jquery 内部数据?

asp.net - 如何在 ASP.NET MVC5 中将字符串从 Controller 传递到 View

javascript - 如果定义为var,如何调用函数调用?