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

时间:2016-05-12 11:27:22

标签: javascript jquery asp.net cookies checkbox

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

我尝试过将函数设为$(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>

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

1 个答案:

答案 0 :(得分:1)

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

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