开发者

Can I have onClick() event for <h1> to <h6> tags?

I want to have the onClick() event on <h1> to <h6> (any of the heading tags) for running some javascript. Please give me some example that has the o开发者_运维技巧nClick() event in an <h1> tag which shows some alert() message.

Thanks :)


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!


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.


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.


Code :

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

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜