When to use onclick in HTML?

后端 未结 3 630
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 03:35

HI,

For a tag, you can execute javascript through href or onclick.

When should I use onclick instead of href?

for me, only advantage I get with oncli

相关标签:
3条回答
  • 2020-12-12 04:05

    Ideally you won't use either. Ideally your link is a normal hyperlink with an href value referencing a fragment (#foo) or URL. Ideally the link would just work as-is without Javascript, too.

    You'd then use unobtrusive Javascript that attaches itself to links or other DOM elements as needed and only if Javascript is available:

    <a href="/some/action" id="foobar">Do some action!</a>
    
    <script type="text/javascript">
        document.getElementById('foobar').addEventListener('click', function () {
            // do something
        }, false);
    </script>
    
    0 讨论(0)
  • 2020-12-12 04:06

    Don't use either.

    Write unobtrusive JavaScript instead.

    0 讨论(0)
  • 2020-12-12 04:07

    You need onclick when more things should be done than jumping to another page.

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