Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - JavaScript-具有onClick的document.getElementByID(JavaScript - document.getElementByID with onClick)

I'm trying to code a simple game in an HTML document just for fun.(我试图在HTML文档中编写一个简单的游戏只是为了好玩。)

In it, there is an image which adds to your score when clicked.(单击其中的图像会增加您的分数。) I created a simple if statement within the score-adding function which should change the image and what it's onClick value is...(我在分数添加功能中创建了一个简单的if语句,该语句应该更改图像及其onClick值是...) if (foo == 1) { document.getElementById("test").src = "images/test2.png"; document.getElementById("test").onClick = "foo2()"; } ...but it doesn't work.(...但是它不起作用。) The image will be successfully changed, but the actual onClick remains the same.(图像将成功更改,但实际的onClick保持不变。) Checking the console, it throws no errors, either.(检查控制台,它也不会引发任何错误。)   ask by Poyo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The onclick property is all lower-case, and accepts a function , not a string.(onclick属性均为小写字母,并且接受函数 ,而不是字符串。)

document.getElementById("test").onclick = foo2; See also addEventListener .(另请参见addEventListener 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...