onclick not working in external js-file, but in in

2019-05-30 13:35发布

What I want : change text-color to red on text in a <h1>tag with <id="headline">

Anyone that has an idea why the following code does not work, but further down in this question, that code work by moving onclick-event to inline code?

Does not work : following code written in external js-file

function changeColor(){
    document.getElementById("headline").style.color = "red";
}

document.getElementById("headline").onclick = changeColor;

Works : Following code written in external js-file (function is the same):

function changeColor(){
    document.getElementById("headline").style.color = "red";
}

…and this written in inline code:

<h1 id="headline"  onclick="changeColor()">with inline code this text change color on click</h1>

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-30 14:16

Without seeing more of your code, I would assume that you are creating and binding the changeColor() function in a javascript file that is loaded in the <head> of your HTML.

If so, the element with id headline doesn't exist yet (the javascript file is being processed before the HTML has fully loaded), so you are trying to bind to a non-existent element.

If this is the case, either move your script include to the bottom of the <body> element , or wrap the binding in a window.onload function as seen in this jsFiddle.

查看更多
登录 后发表回答