When to use onclick in HTML?

2019-01-20 17:53发布

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 onclick is that you can hide javascript function name and parameters from your visitors.

3条回答
爷、活的狠高调
2楼-- · 2019-01-20 18:37

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

查看更多
Deceive 欺骗
3楼-- · 2019-01-20 18:44

Don't use either.

Write unobtrusive JavaScript instead.

查看更多
贼婆χ
4楼-- · 2019-01-20 18:51

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>
查看更多
登录 后发表回答