[英]I can't figure out how to get my javascript onclick event to work
When I click on the button nothing happens unless I call the function in the html. 当我单击按钮时,除非我在html中调用该函数,否则什么也不会发生。 I am trying to remove all inline javascript.
我正在尝试删除所有内联JavaScript。 I have included the commented-out section of html that works.
我已经包含了html的注释掉部分。 Thanks in advance for the help!
先谢谢您的帮助!
JavaScript: JavaScript:
var welcomeString;
const TEST = 1;
function setWelcomeString() {
"use strict";
welcomeString = prompt("Please enter your name: ", "nobody");
}
function writeOutput() {
"use strict";
document.getElementById("demo").innerHTML = "Hello, " + welcomeString;
}
function main() {
"use strict";
setWelcomeString();
document.getElementById("sayHi").onclick = writeOutput();
}
main();
HTML: HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>**SET TITLE**</title>
<link href="css/style.css" rel="stylesheet">
<script src="firstScript.js"></script>
</head>
<body>
<h1 id="wiggles">TEMPLATE</h1>
<!--<button id="sayHi" onclick="writeOutput()">Say Hi</button>-->
<button id="sayHi">Say Hi</button>
<p id="demo"></p>
</body>
</html>
When you assign a function as a handler for an event, you need to assign the function itself, not execute the function and assign it's return value as you are doing. 当您将函数分配为事件的处理程序时,您需要分配函数本身,而不是执行函数,并在执行操作时分配其返回值。 Change this:
更改此:
document.getElementById("sayHi").onclick = writeOutput(); // parens
To this: 对此:
document.getElementById("sayHi").onclick = writeOutput; // no parens
Here is a jsfiddle link with a working example. 这是带有工作示例的jsfiddle链接 。
You have to add your whole code inside load
, like this 您必须像这样将整个代码添加到
load
window.load = function(){
// your javascript here
};
Also, as jbabey mentioned, use either 另外,如jbabey所述,请使用
document.getElementById("sayHi").onclick = function(){ writeOutput();};
Or 要么
document.getElementById("sayHi").onclick = writeOutput;
You have two issues. 你有两个问题。
The first being covered by jbabey. 第一个被jbabey覆盖。
The second is that firstScript.js appears before your button. 第二个是firstScript.js出现在您的按钮之前。 This is problematic as when you are assigning the
onClick
handler to it. 这是有问题的,因为当您为其分配
onClick
处理程序时。 It doesn't exist in the dom. 它在dom中不存在。
Try putting the entire main script inside window.onload = function () { ... }
or moving it to the bottom of the markup. 尝试将整个主脚本放入
window.onload = function () { ... }
或将其移至标记的底部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.