最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Feb 23, 2014 at 13:38 BernardBernard 4,58019 gold badges59 silver badges93 bronze badges 3
  • possible duplicate of Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events – Lucky Soni Commented Feb 23, 2014 at 13:43
  • I'm new to javascript and I was not able to find it... Anyway thanks for your vote! – Bernard Commented Feb 23, 2014 at 13:45
  • Sure, don't take it personally.. its just to keep the site clean :) cheers! – Lucky Soni Commented Feb 23, 2014 at 16:12
Add a comment  | 

5 Answers 5

Reset to default 5

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>
<button type="button" onclick="myFunction()">Click Me!</button>



<script>
    function myFunction() {
        alert("My First JavaScript");
    }
</script>
  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>
发布评论

评论列表(0)

  1. 暂无评论