我如何解决这个问题“无法读取属性'appendChild'of null”错误? [英] How do I solve this "Cannot read property 'appendChild' of null" error?

查看:1808
本文介绍了我如何解决这个问题“无法读取属性'appendChild'of null”错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用下面的代码,在我的网站上添加幻灯片中的按钮:

I tried to use this code below, which adds buttons in slideshow on my site:

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var id = "views_slideshow_controls_text_next_slideshow-block";
    if (id !== 0) {
        document.getElementById(id).appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    var id1 = "views_slideshow_controls_text_previous_slideshow-block";
    if (id1 !== 0) {
        document.getElementById(id1).appendChild(elem1);
    } else console.log("aaaaa");
}

在首页上,我有幻灯片显示一切正常,但在其他页面错误无法读取null 的属性'appendChild'。

On the front page, where I have slideshow everything works good, but on the other pages the error Cannot read property 'appendChild' of null occurs.

推荐答案

元素尚未附加,因此它等于null。 Id永远不会= 0.当你调用getElementById(id)时,它是null,因为它不是dom的一部分,除非你的静态id已经在DOM上了。通过控制台进行呼叫以查看它返回的内容。

The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.

这篇关于我如何解决这个问题“无法读取属性'appendChild'of null”错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆