未捕获的TypeError:无法设置属性' textContent' null

时间:2017-03-05 00:30:36

标签: javascript html

我在尝试按照Udemy JS项目时遇到此错误。我的全职开发人员中有3位朋友无法弄明白,我已经阅读了10 - 15篇有关此错误的StackOverflow文章及其变体,似乎没有任何内容适用。

这是常见的错误:

Uncaught TypeError: Cannot set property 'textContent' of null
    at Object.displayBudget (app.js:177)
    at updateBudget (app.js:219)
    at ctrlAddItem (app.js:236)
    at HTMLDocument.<anonymous> (app.js:205)

看起来非常简单,但是在关闭正文标记之前将脚本放置在HTML底部并且没有通过查询的名称匹配元素的常见解决方案不适用。我已经对这两件事进行了三重检查,甚至在某人的建议下添加了JQuery .ready功能,以确保页面正在加载。

我已在控制台中为上面引用的所有行设置了断点并逐步执行代码,并且在失败之前直接看起来我的变量已定义且不是NULL。见附图或下图。

Code Step Through

预算_值&#39;完全存在于html中。

<body>

        <div class="top">
            <div class="budget">
                <div class="budget__title">
                    Available Budget in <span class="budget__title--month">%Month%</span>:
                </div>

                <div class="budget__value">+ 2,345.64</div>

这是我的代码Fiddle。我还想把它推到Github(/ Laflamme02 / BudgetApp),如果你想看看我是如何进入这里的。

我至少在2周内一直在努力解决这个问题,所以无论谁帮我解决这个问题都将是我最喜欢的人。

2 个答案:

答案 0 :(得分:2)

您忘记了DOMString.budgetLabel中班级名称前面的点。它应该是:

document.querySelector('.budget__value').textContent = obj.budget

从您的JSFiddle中,您可以看到您忘记将点放在其他几个字符串的前面:incomeLabelexpensesLabelpercentageLabel。这四个都是简单的修复。

var DOMstrings = {
    inputType:          '.add__type',
    inputDescription:   '.add__description',
    inputValue:         '.add__value',
    inputBtn:           '.add__btn',
    incomeContainer:    '.income__list',
    expensesContainer:  '.expenses__list',
    budgetLabel:        'budget__value',
    incomeLabel:        'budget__income--value',
    expensesLabel:      'budget__expenses--value',
    percentageLabel:    'budget__expenses--percentage'
};

答案 1 :(得分:0)

const myHeading=document.querySelector('h1');
myHeading.textContent='Hello World';
<html>
    <head>
        <title>

        </title>
        
    </head>
    <body>
        <h1></h1>
        <script src="main.js"></script>
    </body>
</html>