Can I have onClick() event for

to

tags?

2019-06-20 05:22发布

问题:

I want to have onClick() event on <h1> to <h6> (any of heading tags) for running some javascript. Please give me some example to have onClick() event in <h1> which shows some alert() message.

Thanks :)

回答1:

It's called the inline event registration model. And yes, you can do more or less what you're asking after.

But please don't do this.

It's ancient and reliable, yes. But the drawback is that it requires you to put your JS behaviors into your XHTML structure.

You are much better off using the following idiom:

element.onclick = doSomething;

In jQuery, this might look something like:

  $(":header").click(function(){
     alert('Handler for .click() called.')
   });

Good luck!



回答2:

If you're willing to use jQuery, it's easy to handle.

$('h1, h2, h3, h4, h5, h6').click(function(){
    //do something on click
});

If you want a different function on each level of header, you can easily do that too:

$('h1').click(function(){
    //do something on click
});

$('h2').click(function(){
    //do something on click
});

//Etc.


回答3:

If you don't want to use a library like jQuery, here's one way to handle it:

var tags = ['h1','h2','h3','h4','h5','h6'];

for( var i in tags ){
    var these = document.getElementsByTagName(tags[i]);
    if( these.length ){
        for( var n=0,m=these.length;n<m;n++ ){
          these[n].addEventListener('click',function(){ 
            alert('hello'); 
          },false);
        }  
    }
}

Example: http://jsfiddle.net/redler/HvvVQ/

As @Shadow Wizard points out in the comments, IE uses attachEvent instead of addEventListener, so to make this work in all browsers, you'll need some code that works both ways. If you want to avoid the rabbit hole of browser differences and verbosity, the same can be accomplished in jQuery like this, for example:

$('h1,h2,h3,h4,h5,h6').click( function(){
  alert('hello');
});

Even more concise, thanks to @Kobi's comment, is :header:

$(':header').click( function(){...} );

I'd recommend going with a library of your choosing to make this sort of thing much easier.



回答4:

Code :

<script>
    function handleOnClick() {
    alert("Clicked on h1 tag");
  }
</script>

<h1 onclick="handleOnClick()">
  I am h1 tag
</h1>


回答5:

Use 'function' keyword to create function() and any code of logic comes inside the script tags.

<html>
        <head> 
            <title>Understanding Tags in JS </title>
        </head>
        <body>
            <h1> Welcome to JavaScript Tutorial </h1>
            <h2 id = 'h2tag' onclick = "clickedMe()"> Click me to change </h2>
            <script>
                function clickedMe() {
                document.getElementById('h2tag').innerHTML = 'Alas ! I am clicked!'
            }
            </script>
        </body>
    </html>