[英]Javascript onClick event not working to log on the console
I know I'm overlooking something but I'm stuck on knowing what I'm doing wrong. 我知道我忽略了一些东西,但我不知道自己做错了什么。 Can't seem to get the console to print out ( I'm eventually working on adding a box to the screen).
似乎无法打开控制台(我最终正在为屏幕添加一个盒子)。 I'm using Chrome btw:
我正在使用Chrome btw:
HTML HTML
<button id="1" class="hot"></button>
JS JS
function addBox() {
console.log("hello");
}
var clickBox = document.getElementById("1");
clickBox.onClick = addBox;
DOM properties are case sensitive (unlike HTML attributes) and the correct name of the property is onclick
: DOM属性区分大小写(与HTML属性不同),并且属性的正确名称为
onclick
:
clickBox.onclick = addBox;
Learn more about the different ways of binding event handlers. 详细了解绑定事件处理程序的不同方法。
function addBox() { console.log("hello"); } var clickBox = document.getElementById("1"); clickBox.onclick = addBox;
.hot { width: 100px; height: 100px; border: 3px solid black; background-color: pink; }
<button id="1" class="hot"></button>
Try 尝试
clickBox.onclick = addBox;
or 要么
clickBox.addEventListener('click', addBox);
I do not know of any native onClick
method for DOM elements in JavaScript. 我不知道JavaScript中DOM元素的任何原生
onClick
方法。
You could do an event attribute in your HTML <button onclick="addBox()">
. 您可以在HTML
<button onclick="addBox()">
执行事件属性。
Or you could do clickBox.addEventListener('click', addBox);
或者你可以做
clickBox.addEventListener('click', addBox);
. 。
First, your ID should begin with a letter (if you plan to have HTML4 compatibility). 首先,您的ID应以字母开头(如果您打算兼容HTML4)。 Second, if you want to define an event using JS (without a library such as jQuery), you should use
addEventListener
. 其次,如果要使用JS定义事件(不使用jQuery等库),则应使用
addEventListener
。 Or you can simply go the route of adding onclick
directly to the element ( onclick="addBox()"
). 或者你可以直接添加
onclick
到该元素的路径( onclick="addBox()"
)。 Finally your onclick
should all be lowercase (as JS property keys are case sensitive). 最后你的
onclick
应该都是小写的(因为JS属性键区分大小写)。
this this code javascript : 这个代码javascript:
var clickBox = document.getElementById("1");
clickBox.onclick=addBox;
function addBox() {
console.log("hello");
}
Try giving all the javascript within window.onload tags Like the following: 尝试在window.onload标签中提供所有javascript如下所示:
window.onload = function(){
window.onload = function(){
//Your Code Here//你的代码在这里
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.