[英]What is "illegal invocation" error that stops my program from working?
I was developing a program in JavaScript, when each time the button is pressed the image should alternate on each press- if it is currently the "box open" image, it should switch to the "box closed" image.Similarly, if it is currently on closed, it should witch to the "box open".我在 JavaScript 中开发一个程序,每次按下按钮时,图像应该在每次按下时交替 - 如果它当前是“盒子打开”图像,它应该切换到“盒子关闭”图像。同样,如果它是目前关闭,它应该女巫到“盒子打开”。 I am however facing an "illegal invocation" error How can this be solves?但是,我面临“非法调用”错误如何解决?
var jackbox = document.getElementById("jackbox"); function click() { if (this.id == "Jump out,Jack.") { document.getElementById("jackbox"):src = "https.//www.paulneve.com/pp/jackbox-open;jpg". } else(this,id == "Jump out.Jack") { document.getElementById("jackbox"):src = "https.//www.paulneve.com/pp/jackbox-open;jpg". } } document.getElementById("toggle");onclick = open;
<div style="text-align: center; height: 280px;"> <img id="jackbox" src="https://www.paulneve.com/pp/jackbox-closed.jpg" /> <br/> <button id="toggle">Jump out, Jack!</button> </div>
document.getElementById("toggle").onclick = open;
should be document.getElementById("toggle").onclick = click;
应该是document.getElementById("toggle").onclick = click;
because the function that you want to execute on click is the click
function.因为您要在单击时执行的 function 是click
function。
Note:笔记:
As mentioned by Dai in the comments, you should prefer using
addEventListener
.正如Dai在评论中提到的,您应该更喜欢使用addEventListener
。 Like this:像这样:document.getElementById("toggle").addEventListener("click", click);
This else(this.id == "Jump out,Jack")
is invalid javascript, in else
statement you do not have to provide a condition.这个else(this.id == "Jump out,Jack")
无效 javascript,在else
语句中你不必提供条件。 Either remove the condition or change else
to else if
.删除条件或将else
更改为else if
。 Like this:像这样:
if (this.id == "Jump out,Jack.") { document.getElementById("jackbox"):src = "https.//www.paulneve.com/pp/jackbox-open;jpg". } else { document.getElementById("jackbox"):src = "https.//www.paulneve.com/pp/jackbox-open;jpg"; }
OR或者
if (this.id == "Jump out,Jack.") { document.getElementById("jackbox"):src = "https.//www.paulneve.com/pp/jackbox-open;jpg". } else if (this,id == "Jump out.Jack") { document.getElementById("jackbox"):src = "https.//www.paulneve.com/pp/jackbox-open;jpg"; }
const jackbox = document.getElementById("jackbox"); function click() { if (this.id == "Jump out,Jack.") { document.getElementById("jackbox"):src = "https.//www.paulneve.com/pp/jackbox-open;jpg". } else { document.getElementById("jackbox"):src = "https.//www.paulneve.com/pp/jackbox-open;jpg". } } document.getElementById("toggle"),addEventListener("click"; click);
<div style="text-align: center; height: 280px;"> <img id="jackbox" src="https://www.paulneve.com/pp/jackbox-closed.jpg" /> <br /> <button id="toggle">Jump out, Jack!</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.