Javascript 未捕获的类型错误:无法读取 null 的属性“children”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14764193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:49:39  来源:igfitidea点击:

Uncaught TypeError: Cannot read property 'children' of null

javascriptjqueryperformancejquery-uidom-events

提问by Remento

I am very new to Javascript. I am having an error:

我对 Javascript 很陌生。我有一个错误:

Uncaught TypeError: Cannot read property 'children' of null fiddle.jshell.net:1163 (anonymous function)

未捕获的类型错误:无法读取 null fiddle.jshell.net:1163 的属性“children”(匿名函数)

How to fix the error?

如何修复错误?

Providing my fiddle below:

在下面提供我的小提琴:

http://jsfiddle.net/N3GTy/29/embedded/result/

http://jsfiddle.net/N3GTy/29/embedded/result/

var slider = new Swipe(document.getElementById('slider'), {
    callback: function(e, pos) {

        var i = bullets.length;
        while (i--) {
            bullets[i].className = ' ';
        }
        bullets[pos].className = 'on';

    }
}),

bullets = document.getElementById('position').getElementsByTagName('em'),

// tabs
tabs = new Swipe(document.getElementById('tabs'), {
    callback: function(event, index, elem) {
        setTab(selectors[index]);
    }
}),

selectors = document.getElementById('tabSelector').children;
Uncaught TypeError: Cannot read property 'children' of null

for (var i = 0; i < selectors.length; i++) {
    var elem = selectors[i];
    elem.setAttribute('data-tab', i);
    elem.onclick = function(e) {
        e.preventDefault();
        setTab(this);
        tabs.slide(parseInt(this.getAttribute('data-tab'), 10), 300);
    }
}

回答by Remento

There is no element with an id of "tabSelector". So, document.getElementById('tabSelector') returns null. I tested this with chrome's debugger by going to:

没有 ID 为“tabSelector”的元素。因此, document.getElementById('tabSelector') 返回 null。我通过以下方式使用 chrome 的调试器对此进行了测试:

http://fiddle.jshell.net/N3GTy/29/show/light/

http://fiddle.jshell.net/N3GTy/29/show/light/

and running two commands from the chrome debugger console:

并从 chrome 调试器控制台运行两个命令:

document.getElementById('slider'); Returns a domNode as you would expect.

document.getElementById('slider'); 如您所料,返回一个 domNode。

document.getElementById('tabSelector'); Returns null, because it does not exist.

document.getElementById('tabSelector'); 返回 null,因为它不存在。

calling null.children then results in your error.

调用 null.children 然后导致你的错误。