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

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

问题描述

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

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");
}

在首页上,我有幻灯片,一切正常,但在其他页面上,出现错误 Cannot read property 'appendChild' of null.

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.

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

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