Javascript“Uncaught TypeError:无法设置属性'onclick'of null”

时间:2015-07-26 02:17:10

标签: javascript jquery html css html5

这是我在使用JavaScript代码时遇到的问题。

我有四个不同的HTML文件链接到一个外部javascript文件。在这个外部javascript文件中,我有大约4个函数来控制这4个不同HTML文件中的事件。

现在的问题是这个。假设我将.onclick事件附加到仅存在于contact.html中的按钮。我还在javascript文件中有其他事件函数来控制其他HTML文件中的其他元素。如果我加载contact.html文件,一切正常。但是,如果我加载其他事件函数在contact.html的.onclick事件之后声明的HTML文件,则这些函数根本不起作用。

我在Chrome中打开了开发人员的工具,并在控制台中收到此错误消息。 “未捕获的TypeError:无法设置属性'onclick'为null”

我检查了外部javascript文件中指示的错误,错误是指为仅存在于contact.html中的按钮声明的变量。

我假设发生的事情是,由于浏览器无法在about.html中找到此变量,因此它会停止阅读脚本的其余部分。

以下是我为解决问题所做的工作。

1)我将整个代码包装在window.onload = function(){};中,没有任何效果。

2)我只从js文件中删除了contact.html的.onclick事件的函数,以及在此工作之后的代码。

3)要查看.onclick事件的代码是否有任何错误,我将此事件函数放在contact.html文件的末尾,一切正常,没有任何错误。

考虑到我尝试的所有内容以及我从Chrome中的开发人员工具获得的错误消息,我认为如果浏览器看到为另一个HTML文件中的元素声明的变量,则浏览器会考虑它是一个错误,因此停止执行脚本的剩余部分。

我可能错了,并且没有任何关于如何解决这个问题的线索,这就是我在这里发布这个问题的原因。

只是澄清一些事情,完成以下事情

1)链接到具有正确文件路径的外部javascript文件的脚本标记位于每个HTML文件的body标记的末尾。

2)我尝试用window.onload或$(document).ready(main)包装所有东西; (当然有链接到jQuery CDN。)

这是我的代码:

window.onload = function () {

// for INDEX.HTML page

var pg = document.getElementById("main_pg");
var text = document.getElementById("main_slide");
var box = document.getElementById("slider");

setTimeout(function() {
    pg.innerHTML = "Capturing Nature";
    pg.style.fontSize = "2em";
    box.style.background ="#7FB030"
    box.style.border = "3px solid #7FB030";
}, 2500);

// for GALLERY.HTML page

var action = document.getElementsByClassName("mouse");

var galleryHover = function () {
    for (i = 0; i < action.length; i++) {
        action[i].onmouseover = function () {
            var source = this.getAttribute("href");
            var target = document.getElementById("target");
            target.src = source;
        };
    };
};
galleryHover();

var addon = document.getElementById("mybutton");

addon.onclick = function () {
    var file_name = document.getElementById("file_name").value;
    var list = document.createElement("li");
    var anchor = document.createElement("a");
    anchor.setAttribute("href","images/"+file_name);
    anchor.setAttribute("class", "mouse");
    var new_img = document.createElement("img");
    new_img.setAttribute("src", "images/"+file_name);
    anchor.appendChild(new_img);
    list.appendChild(anchor);
    var append_target = document.getElementById("gallery_list");
    append_target.appendChild(list);
    galleryHover();
};

// for ABOUT.HTML page

var set_date = function () {
    var nd = new Date();
    var sm = nd.getMonth();
    var month_array = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    var cm = month_array[sm];
    var cd = nd.getDate();
    var cy = nd.getFullYear();

    var today_date = document.getElementById("today_date");
        today_date.innerHTML = cm + " " + cd + ", " + cy;
};
set_date();

var bio_img = document.getElementsByClassName("bio_img");
var bio_target = document.getElementById("bio");
for (i = 0; i < bio_img.length; i++) {
    (function(m) {
        bio_img[i].onmouseover = function() {
            bio_target.innerHTML = "";
            var new_bio = document.createElement("img");
            var new_index = m + 1;
            var new_path = "images/bio" + new_index + ".jpg";
            new_bio.setAttribute("src", new_path);
            bio_target.appendChild(new_bio);
        };
    })(i);
};

// for CONTACT.html page

var input_fields = document.getElementsByClassName("input_content");
var warning_message = document.getElementsByClassName("warning_message");
var input_button = document.getElementById("submit");
input_button.onclick = function (e) {
    for (i = 0; i <= input_fields.length; i++) {
        var input_value = input_fields[i].value;
        var value_length = input_value.length;
        if (value_length == 0) {
            e.preventDefault();
            var warning = warning_message[i];
            warning.innerHTML = "This field is required.";
        } else if (value_length > 0) {
            var warning = warning_message[i];
            warning.innerHTML = "";
            };
        };
    };
};

这是gallery.html页面的HTML代码,工作正常。

<!DOCTYPE html>
<html>
<head>
<title>RadicalPhoto Gallery</title>
<link href='http://fonts.googleapis.com/css?family=Gruppo' rel='stylesheet'>
<link type="text/css" rel="stylesheet" href="css/radicalphoto.css">
</head>
<body>
<div id="header">
    <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="gallery.html">Gallery</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="contact.html">Contact</a>
    </ul>
    <h1>RadicalPhoto</h1>
</div>
<div id="main_wrapper">
    <div id="content">
        <h2>Gallery</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Store an image in images folder and Enter the file name below to insert a new image in the gallery</p>
        <p>Name:
            <input type="text" name="visitor_name" id="file_name" placeholder="cat_thumb.jpg">
        </p>
        <button id="mybutton">Try it</button>
        <div id="gallery">
            <ul id="gallery_list">
                <li>
                    <a class="mouse" href="images/blue_dress.jpg">
                        <img src="images/blue_dress_thumb.jpg">
                    </a>
                </li>
                <li>
                    <a class="mouse" href="images/boxer.jpg">
                        <img src="images/boxer_thumb.jpg">
                    </a>
                </li>
                <li>
                    <a class="mouse" href="images/country_boy_relaxing.jpg">
                        <img src="images/country_boy_relaxing_thumb.jpg">
                    </a>
                </li>
                <li>
                    <a class="mouse" href="images/eye.jpg">
                        <img src="images/eye_thumb.jpg">
                    </a>
                </li>
                <li>
                    <a class="mouse" href="images/ice_swim.jpg">
                        <img src="images/ice_swim_thumb.jpg">
                    </a>
                </li>
                <li>
                    <a class="mouse" href="images/sitting.jpg">
                        <img src="images/sitting_thumb.jpg">
                    </a>
                </li>
            </ul>
            <p>
                <img id="target" src="images/blue_dress.jpg" alt="">
            </p>
        </div>
    </div>
    <div id="footer">
        <p>All content &copy; Copyright</p>
    </div>
</div>
<script src="js/main.js"></script>
</body>
</html>

这是about.html页面,这是javascript停止工作的地方,给我上面提到的错误消息。

<!DOCTYPE html>
<html>
<head>
<title>RadicalPhoto About</title>
<link href='http://fonts.googleapis.com/css?family=Gruppo' rel='stylesheet'>
<link type="text/css" rel="stylesheet" href="css/radicalphoto.css">
</head>
<body>
<div id="header">
    <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="gallery.html">Gallery</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="contact.html">Contact</a>
    </ul>
    <h1>RadicalPhoto</h1>
</div>
<div id="main_wrapper">
    <div id="content">
        <h2>About RadicalPhoto</h2>
        <p>Today is <span id="today_date">July 17, 2015</span>. Stay tuned, we have exciting news about our company coming in a few more weeks!</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <h3>Our Team</h3>
        <p id="bios">
            <a class="bio_img" href="sheila.html">Sheila</a> (President) | 
            <a class="bio_img" href="frank.html">Frank</a> (Vice President) | 
            <a class="bio_img" href="joanne.html">Joanne</a> (Senior Photographer)
        </p>
        <div id="bio">
        </div>
    </div>
    <div id="footer">
        <p>All content &copy; Copyright</p>
    </div>
</div>
<script src="js/main.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

在使用变量之前,请检查它们。然后,如果当前页面中不存在给定的DOM元素,则脚本不会导致错误并中止执行。这是一个例子。

var addon = document.getElementById("mybutton");
if (addon) {
    addon.onclick = function () {
        var file_name = document.getElementById("file_name").value;
        var list = document.createElement("li");
        var anchor = document.createElement("a");
        anchor.setAttribute("href","images/"+file_name);
        anchor.setAttribute("class", "mouse");
        var new_img = document.createElement("img");
        new_img.setAttribute("src", "images/"+file_name);
        anchor.appendChild(new_img);
        list.appendChild(anchor);
        var append_target = document.getElementById("gallery_list");
        append_target.appendChild(list);
        galleryHover();
    };
}

您还可以通过将一些逻辑放入一个通用函数来使代码更紧凑:

function addClickHandler(id, fn) {
    var obj = document.getElementById(id);
    if (obj) {
        obj.addEventListener("click", fn);
    }
}

然后,您可以使用该函数添加所有事件处理程序,如下所示:

addClickHandler("mybutton", function(e) {
    var file_name = document.getElementById("file_name").value;
    var list = document.createElement("li");
    var anchor = document.createElement("a");
    anchor.setAttribute("href","images/"+file_name);
    anchor.setAttribute("class", "mouse");
    var new_img = document.createElement("img");
    new_img.setAttribute("src", "images/"+file_name);
    anchor.appendChild(new_img);
    list.appendChild(anchor);
    var append_target = document.getElementById("gallery_list");
    append_target.appendChild(list);
    galleryHover();
});