链接执行javascript代码的正确方法 [英] Proper way for links to execute javascript code

查看:16
本文介绍了链接执行javascript代码的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道有 4 种主要方法可以从链接执行 javascript 代码.对于我的要求,我需要这样做而不会将屏幕移动到任何地方(链接到 # 并且不返回 false 是不好的).如果可能的话,执行的 javascript 代码的 SEO 也很重要.那么正确的做法是什么?

So there are 4 main methods I'm aware of to execute javascript code from a link. For my requirements, I need to do so without moving the screen anywhere (linking to # and not returning false is bad). SEO for the executed javascript code, if possible, is important too. So what's the right way to do this?

方法 1(需要确保 myCode() 始终返回 false):

method 1 (need to make sure myCode() returns false always):

<a href="#" onclick="return myCode();">execute</a>

方法2(似乎最有意义?):

method 2 (seems to make the most sense?):

<a href="javascript:myCode();">execute</a>

方法3:

<a href="javascript:void(0);" onclick="myCode();">execute</a>

方法 4(在语义上不像其他我认为的那样令人愉快):

method 4 (not as pleasant semantically as the others I think):

<span id="executeMyCodeLink" class="link">execute</a>
<script>
$('#executeMyCodeLink').click(myCode);
</script>

使用方法4,你当然也可以使用onclick..

with method 4, you can use onclick as well of course..

推荐答案

您使页面不跳转并使用带有 href 的a"标签和使用 preventDefault 的方法 4.

You make the page not jump and use an "a" tag with an href and method 4 using preventDefault.

<a id="executeMyCodeLink" href="#">execute</a>
<script>
  $('#executeMyCodeLink').click(function(event) {
    event.preventDefault();
    myCode();
  });
</script>

包含 href 很重要,因为链接样式不正确,否则您的 html 将无法验证.

It's important to include an href because links won't style properly and your html won't validate otherwise.

这篇关于链接执行javascript代码的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆