简体   繁体   中英

Which HTML tags can be used with onClick?

Which HTML tags can have an onclick event and which cannot? If there are tags where I cannot include an onclick event I want to know why not?

onclick="func()"

Are there any rules that you should adhere to?

All HTML elements can have an onclick attribute.

See the HTML 5 specification for confirmation.

(Of course, some elements are not rendered by default so you would have to alter their display properties with CSS before they can be clicked on to trigger the event handler).

'"I have the right to do anything," you say -- but not everything is beneficial' - Apostle Paul, 1 Corinthians 6:12

Compare the comments on this post and the resulting link to the MDN web docs which strongly imply that elements such as <div> and <span> should not be used for click-actions because they "do not inherently represent anything" and "It should be used only when no other semantic element is appropriate."

You'll see that while it's possible to attach an onclick to practically anything, some elements have further support for being clicked (or, rather, preventing clicks) and other elements don't.

So, I would recommend that the question be re-phrased to read, "Which HTML tags have full support for onClick?" or something similar. <input> would be a good example of a tag with full support, and <span> , therefore, would not.

I, too, would very much like to find a list of HTML tags that are "first-class click citizens" so I can choose my web elements better.

Any element can have an onclick event via ID or class. Using jQuery, this is very easy:

// Talk to any element with a unique ID of "myElementId".
$('#myElementId').on('click', function(event){
    alert('CLICK');
    // do something else.
    event.preventDefault();
});

// Talk to any element with a class of "myClassElement".
$('.myClassElement').on('click', function(event){
    alert('CLICK');
    // do something else.
    event.preventDefault();
}

// Talk to the <header> element.
$('header').on('click', function(event) {
    alert('CLICK');
    // do something else.
    event.preventDefault(); 
)}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM