简单.显示函数在页面加载时不显示DIV

Simple .Show function not displaying DIV on page load

本文关键字:显示 DIV 加载 函数 简单      更新时间:2023-09-26

我的页面上有一个复选框"cbxShowNotifications"。如果在页面加载时选中了它,我想显示"树状视图"

.aspx页面:

<html> 
      <body>
        <form>
           <asp:CheckBox ID="cbxShowNotifications" runat="server"/>Show Notifications
           <div id="treeview"></div>
        </form>
        <script src="../Scripts/jquery.min.js" type="text/javascript"> </script>
        <script src="../Scripts/kendo.web.min.js" type="text/javascript"> </script>
        <script src="../Scripts/NotificationsTreeView.js" type="text/javascript"> </script>
        <script type="text/javascript">
            $(document).ready(function()
            {
                showOrHide();
            });
        </script>
        <script type="text/javascript">
            $(document).ready(function()
            {
                CreateNotificationTree(<%= UserId.ToString(CultureInfo.InvariantCulture) %>);
            });
        </script>
    </body>
</html>

JavaScript文件:

function CreateNotificationTree(userId)
{
    var data = new kendo.data.HierarchicalDataSource({
        transport: {
            read: {
                url: "../api/notifications/byuserid/" + userId,
                contentType: "application/json"
            }
        },
        schema: {
            model: {
                children: "notifications"
            }
        }
    });
    $("#treeview").kendoTreeView({
        dataSource: data,
        loadOnDemand: true,
        dataUrlField: "LinksTo",
        checkboxes: {
            checkChildren: true
        },
        dataTextField: ["notificationType", "NotificationDesc"],
        select: treeviewSelect
    });
    function treeviewSelect(e)
    {
        var node = this.dataItem(e.node);
        window.open(node.NotificationLink, "_self");
    }
}
$('#cbxShowNotifications').on('change', function()
{
    debugger;
    var tview = $('#treeview');
    if ($(this).prop('checked'))
    {
        tview.show();
    }
    else
    {
        tview.hide();
    }
});
function showOrHide()
{
    debugger;
    var tview = $('#cbxShowNotifications');
    if ($(this).prop('checked'))
    {
        tview.show();
    }
    else
    {
        tview.hide();
    }
}

问题是,当页面加载并且选中复选框时,树视图是不可见的。我做错了什么?

顺便说一句,在加载页面后,如果我取消选中复选框,树就会消失,如果我选中它,它就会出现。

所以这只发生在页面加载时,这让我相信这是一个何时执行的问题。

复选框cbxShowNotifications是一个.net服务器控件。因此,ID将不会保持不变。观察DOM中ID以Page&控制信息,即类似于"master_ctrl_cbxShowNotifications"的信息

我建议你给它加一个类&使用类作为选择器。

<asp:CheckBox ID="cbxShowNotifications" CssClass="chkBoxNotif" runat="server"/>
$('.chkBoxNotif').on('change', function(event) {
    //Do something
});

在函数showOrHide

更改:

if ($(this).prop('checked'))

if ($('#cbxShowNotifications').prop('checked'))

this值不是复选框。