未捕获的TypeError:无法读取null的属性“ hide”

时间:2019-01-09 03:19:42

标签: javascript

这是我的代码

var ReportFolderListUtil = {
    confirmBox2:null,
    showConfirmation: function(reportFolderId){
        console.log(reportFolderId);

        this.confirmBox2 = Lobibox.confirm({
            delay:false,
            title : 'Confirmation',
            msg : "Please take note that reports created under this folder will also be deleted. Are you sure you want to delete this folder?",
            buttons: {
                yes: {
                    'class': 'btn btn-success',
                    closeOnClick: false
                },
                no: {
                    'class': 'btn btn-default',
                    closeOnClick: true
                }
            },
            callback: function ($this, type, ev) {
                if (type === 'yes')
                    window.location.href = "/report/remove-folder/"+reportFolderId+".html";
                    ReportFolderListUtil.hideConfirmation();
                    JobUtil.showLoading("deleteReport","deleting folder.");
                }
            }
        })
    },
    hideConfirmation: function(){
        this.confirmBox2.hide();
    }

我一直在控制台上收到此错误:

enter image description here

2 个答案:

答案 0 :(得分:1)

据我所知,您的代码的问题在于您在ReportFolderListUtil.hideConfirmation方法之前先调用ReportFolderListUtil.showConfirmation方法,因此ReportFolderListUtil.confirmBox2不会在{内用this.confirmBox2 = Lobibox.confirm重新初始化{1}}方法主体,它是每个showConfirmation变量声明中的null

根据您的需求,您可以

a)以

的方式保护ReportFolderListUtil
hideConfirmation

b)或定义隐藏方法存根

hideConfirmation: function() {
    this.confirmBox2 && this.confirmBox2.hide();
}

c)或查看方法调用的顺序,以免在显示之前调用hide ...

答案 1 :(得分:0)

在此上下文中执行“ showConfirmation”之前,confirmBox2将没有值。您在回调中的“ if”上也缺少大括号。

在执行功能时牢记对象状态很重要。 为防止发生致命错误,我建议您进行更多的空检查 if( confirmbox2 ) { //execute request }