当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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.

网友答案:

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)

<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.

网友答案:

You can invoke alert using:

<button type="button" onclick="javascript:alert('My First JavaScript');">Click Me!</button>
网友答案:
  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.
网友答案:

HTML

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

<script>
function myFirst() {
    alert("My First JavaScript");
}
</script>
网友答案:
<button type="button" onclick="myFunction()">Click Me!</button>



<script>
    function myFunction() {
        alert("My First JavaScript");
    }
</script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: