Better way to call javascript function in a tag

前端 未结 4 417
时光说笑
时光说笑 2020-12-08 13:28

Which of the following ways is a better way to call a js function from an a tag?

LINK

4条回答
  •  青春惊慌失措
    2020-12-08 13:52

    Some advantages to the second option:

    1. You can use this inside onclick to reference the anchor itself (doing the same in option 1 will give you window instead).

    2. You can set the href to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to use onclick="return someFunction();" and return false from inside the function or onclick="return someFunction(); return false;" to prevent default action).

    3. I've seen weird stuff happen when using href="javascript:someFunction()" and the function returns a value; the whole page would get replaced by just that value.

    Pitfalls

    Inline code:

    1. Runs in document scope as opposed to code defined inside

提交回复
热议问题