javascript 如何将脚本添加到同一文件中 HTML 中的按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21968922/
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-27 22:06:40  来源:igfitidea点击:

How to add script to a button in HTML in same file?

javascripthtml

提问by Bernard

This may be a basic question. I have a button which is

这可能是一个基本问题。我有一个按钮

<button type="button">Click Me!</button>


And then I have a script which is:


然后我有一个脚本,它是:

<script>
alert("My First JavaScript");
</script>



To call this script I can say onclick call another php or html file. But I want to add this script to the same file instead of adding a new file. Any suggestion will be appreciated.

要调用这个脚本,我可以说 onclick 调用另一个 php 或 html 文件。但我想将此脚本添加到同一个文件中,而不是添加一个新文件。任何建议将不胜感激。

采纳答案by Lucky Soni

Couple of ways:

几种方式:

1st

第一

<button type="button" onclick="clickHandler()">Click Me!</button>

<script>
    function clickHandler() {
      alert("something");
    }
</script>

2nd(if you are using something like jQuery)

第二个(如果您使用的是 jQuery 之类的东西)

<button id="btn" type="button">Click Me!</button>

$('#btn').click(function() {
    alert('something')//
});

you may also do this in plain javascript.. just search for add event handler and you will get plenty of cross browser ways of doing this.

你也可以用普通的 javascript 来做这件事。只需搜索添加事件处理程序,你就会得到很多跨浏览器的方法来做到这一点。

回答by Unknown

You can invoke alert using:

您可以使用以下方法调用警报:

<button type="button" onclick="javascript:alert('My First JavaScript');">Click Me!</button>

回答by Matú? Bartko

<button type="button" onclick="myFunction()">Click Me!</button>



<script>
    function myFunction() {
        alert("My First JavaScript");
    }
</script>

回答by Jamie Tabone

  1. Make the script type="text/javascript"
  2. Close the alert inside a function example function temp(){....}
  3. add onClick in the button section i.e.
  1. 使脚本类型=“text/javascript”
  2. 关闭函数示例函数 temp(){....} 中的警报
  3. 在按钮部分添加 onClick ie

回答by Jonathan

HTML

HTML

<button onclick="myFirst()" type="button">Click Me!</button>

<script>
function myFirst() {
    alert("My First JavaScript");
}
</script>