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

走远了吗. 提交于 2020-01-23 17:25:06

问题


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:


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.



来源:https://stackoverflow.com/questions/17437118/onclick-not-working-in-external-js-file-but-in-inline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!