Is onclick attribute redundant after href attribute?

时间:2015-12-10 01:28:54

标签: javascript html

In the below code,

<div id="content">
    Here is my <a href="javascript:(function(){ 
        _my_script=document.createElement('SCRIPT');
        _my_script.type='text/javascript';
        _my_script.src='file:///D:/Access/bookmark/bmlet.js';
        document.getElementsByTagName('head')[0].appendChild(_my_script);})();">
    bookmarklet</a>
</div>

in addition to bookmark functionality, javascript: URI scheme allows you to invoke the JavaScript code that can inspect/update DOM of current page on click event of anchor tag(a),

Another example, where,

<a href="JavaScript:void(0)" onClick="alert('Hello');">Say Hello</a>?

can be written as,

<a href="JavaScript:{alert('Hello');}void(0)">Say Hello</a>?

So, What is the purpose of html attribute onclick?

1 个答案:

答案 0 :(得分:1)

The onclick attribute appears redundant because you are using a link as a button. That is semantically incorrect and misleading: a link navigates to a different location, a button performs an action. If you want to perform an action, use a button element.

If you need a link, then the href attribute should be the link target and the onclick should be used to attach additional behaviour.

Edit

Additional information regarding the purpose of links and buttons.

The HTML 5.1 specification regarding links:

If the a element has an href attribute, then it represents a hyperlink (a hypertext anchor) labeled by its contents.

A button has no other purpose than to be activated, which is inferred by:

The type attribute controls the behaviour of the button when it is activated.

It is also considered poor practice to insert complex scripts into HTML attributes as it makes maintenance more difficult, contributing to technical debt.