javascript 如何处理javascript中的点击事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5460733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:16:09  来源:igfitidea点击:

How to handle click event in javascript?

javascriptdesign-patternsarchitecture

提问by Stack Guru

Today is my first day at a new job (a Front End Lead on a large website.) One of my tasks is to implement a button that fires an event when it's clicked. I had no clue, so after googling a bit, I came up with this:

今天是我从事新工作的第一天(大型网站的前端负责人)。我的任务之一是实现一个按钮,该按钮在单击时触发事件。我不知道,所以在谷歌搜索了一下之后,我想出了这个:

<html>
<head>
<script type="text/javascript">
function popup(); 
{
    alert("Hello World") ==> alert("Hello World");
}
</script>
</head>
<body>

<input type="button" value="Click Me!" onclick="popup()"></input><br></br>

</html>    
</body>

The problem is, when I click my button, nothing happens.

问题是,当我单击按钮时,什么也没有发生。

EDITUpdated based on MICHEL's comments

编辑根据米歇尔的评论更新

回答by Naftali aka Neal

remove the semi-colon:

删除分号:

function popup()
{
    alert("Hello World")
}

that should work ^_^

那应该工作^_^

see it working here: http://jsfiddle.net/maniator/fNeJh/

看到它在这里工作:http: //jsfiddle.net/maniator/fNeJh/

回答by Matt Ball

Your HTML is invalid. Change

您的 HTML 无效。改变

</html>    
</body>

to

</body>
</html>

Also, the <br>tag has no content, so you don't need a closing tag at all (for HTML) or you can write it as a self-closing tag: <br/>.

此外,该<br>标签没有内容,因此您根本不需要结束标签(对于 HTML),或者您可以将其编写为自结束标签:<br/>

As far as the JavaScript error goes, Neal's answer is correct.

就 JavaScript 错误而言,Neal 的回答是正确的。

回答by Scherbius.com

This should work

这应该工作

<html>
<head>
</head>

<body>

<script type="text/javascript">
function popup() 
{
    alert("Hello World");
}
</script>

<input type="button" value="Click Me!" onclick="popup()"><br/><br/>

</body>
</html>

回答by Michel

Remove semi-colon after

删除分号后

Bad :

坏的 :

function popup(); 

Good :

好的 :

function popup()

You might want to add one after alert("Hello World") ==> alert("Hello World");

您可能想在 alert("Hello World") ==> alert("Hello World"); 之后添加一个

回答by Maxim Dsouza

function should not have a semi colon after its declaration ... A simple tutorial on javascript would give you a start on javascript...

函数在声明后不应该有分号......一个简单的javascript教程会让你开始学习javascript......