What if I use #! instead of # in href of anchor tag ?

后端 未结 1 633
面向向阳花
面向向阳花 2020-12-30 06:02

I have used #! in href of a tag in my website. It does not throws the user on top of the page if he/she clicks the link. But my question is, is it legal?

<         


        
相关标签:
1条回答
  • 2020-12-30 06:43

    It seems your goal is to create something that the user can click on in order to trigger some JavaScript and you don't want side effects (like navigating to the top of the page).

    is it legal?

    • It is not semantically correct. Links should be links.
    • It is a hack: You are linking to the element with id="!" and depending on the error recovery that happens when that element doesn't exist.
    • It is allowed under the rules of what constitutes valid HTML.
    • It is probably OK according to the various bits of accessibility legislation about the work which don't generally care if something works without JavaScript

    The correct way to present a clickable control which exists only to bind JavaScript to is to use a button.

    <button type="button">Click here</button>
    

    You can apply CSS to make it look however you like though, so don't let "But it I want it to look like a link" stop you.


    A more robust approach would be to use a server side fallback (i.e. a form submission or a link) and to cancel the default behaviour of the control by calling the preventDefault method of the event object.


    Further reading:

    • Everyone has JavaScript, right?
    • Progressive Enhancement
    • Unobtrusive JavaScript
    0 讨论(0)
提交回复
热议问题