未捕获的类型错误:无法读取空值的 'insertAdjacentHTML' 属性。

3

我是一个非常有动力的人,想成为JavaScript开发人员。调试让我感到疲惫不堪。我认为这部分是我们开始的最难的部分。不管怎样; 我在一个项目中。 这是其中的最后一部分。 我遇到了这个错误,但是找不到解决方案。

我的JavaScript代码在这里:

var arayuz = (function(){
    
    var Domstrings = {
        InputType:'.add__type',
        InputDescription:'.add__description',
        InputValue:'.add__value',
        InputBtn:'.add__btn',
        IncomeList:'income__list',
        ExpenseList:'expenses__list'
            
    };

    return {
        getInput: function() {
            return {
                type: document.querySelector(Domstrings.InputType).value, // Will be either inc or exp
                description: document.querySelector(Domstrings.InputDescription).value,
                value: document.querySelector(Domstrings.InputValue).value
            };
        },

        // and the part where I got stuck...

        addListItem: function(obj,type){
            //Default HTML
            var html, newHtml, element;
            if(type == 'inc'){
                element = Domstrings.IncomeList;
                html='<div class="item clearfix" id="income-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">+%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>'
            } else if(type == 'exp'){
                element = Domstrings.ExpenseList;
                html='<div class="item clearfix" id="expense-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">- %value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
            }
            // Change HTML
            newHtml = html.replace('%id%', obj.id);
            newHtml = newHtml.replace('%description%', obj.description);
            newHtml = newHtml.replace('%value%', obj.value);
        
            // YAZILARIN ÖNCESİNE EKLENMESİNİ EKLEYEN HTMLADJACENT METODU KULLANIMI
        
            document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);        
        
        },

        getDomstrings:function(){
            return Domstrings;
        }
       
    } ;       
        
})();
2个回答

7

你的错误实际上意味着你试图在一个为 null 的对象上访问名为 insertAdjacentHTML 的属性(因为 nullundefined 不能有属性)。

只有一行可能会出现这种情况:

document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);

问题在于,您忘记在IncomeListExpenseList选择器前写上点(如果它们是ID,则是#)。

没有这个符号,代码将尝试查找标签名为income__listexpenses__list的元素。

这将导致从.querySelector返回null(因为不存在这样的元素),并且当您尝试在其上调用insertAdjacentHTML时会出现错误。


0

你的代码

IncomeList: 'income__list',

ExpenseList: 'expenses__list'

解决方案

IncomeList: '.income__list', 

ExpenseList: '.expenses__list'

// add dot you've selected class name but missing dot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接