What is the Difference between onclick and href="[removed]function name?

前端 未结 6 1690
别跟我提以往
别跟我提以往 2021-02-10 12:20

Is there any difference between

1 : Link1

and

2 : 

        
相关标签:
6条回答
  • 2021-02-10 12:35

    There is a difference in functionality, the first doesn't attempt to process a link. The second does.

    However, I agree with Coronatus - both methods are not ideal. I would suggest researching unobtrusive JavaScript (perhaps with jQuery) as you could dynamically add a click event to the element.

    0 讨论(0)
  • 2021-02-10 12:43

    If your website requires Javascript in order to function correctly then Javascript in the href is best because it shows the link in the status bar and keeps the code compact. In the href also serves keyboard navigation without the mouse. If your website is required to function without Javascript then you have to use onclick so the href can have a link in it. Adding the action in a separate Javascript file fails to keep code & data bound tightly.

    0 讨论(0)
  • 2021-02-10 12:46

    The onclick version allows you pass 'this' as an argument, so you can refer back to the tag/object the click came from. Not possible with the protocol method:

    <a href="#" onclick="alert(this.innerHTML)">yo yo yo</a>
    

    will spit out an alert popup with "yo yo yo", whereas

    <a href="javascript:alert(this.innerHTML)">yo yo yo</a>
    

    will spit out 'undefined'.

    0 讨论(0)
  • 2021-02-10 12:49

    No performance difference.

    The first is crap because it will fail completely for users without JS enabled.

    The second is still crap, but would be better if the href pointed to a URL for users without JS enabled.

    0 讨论(0)
  • 2021-02-10 12:49

    An href="javascript: doSomething" means you do not have a url to fallback to if the user doesn't have js enabled.

    Therefore, setting href="something.html" and onclick="return doSomething()" is usually considered better because if js is disabled, you can navigate to a new page, but if js is enabled, you can return false to prevent navigation to the link and display something within the same page without a page refresh.

    Even better, don't add the onclick inline, just add js handlers when the page loads. That's the unobtrusive way

    0 讨论(0)
  • 2021-02-10 12:52

    If your element is not actually supposed to link the user someplace, don't make it an anchor element. If you're using <a> tags just to get the underline/cursor change - don't. Use CSS on a <span> (or other element) instead.

    span.link {
      text-decoration: underline;
      color: blue;
      cursor: pointer;
    }
    

    Keep your HTML semantic and use anchor elements only when you want to link the user somewhere.

    0 讨论(0)
提交回复
热议问题