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

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

问题描述

因此,我知道从链接执行JavaScript代码有四种主要方法。对于我的要求,我需要在不移动屏幕的任何地方这样做(链接到#并且不返回false是不好的)。如果可能的话,执行的JavaScript代码的SEO也很重要。那么有什么方法可以做到这一点?



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

 < a href =#onclick =return myCode();>执行< / a> 

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

 < a href =javascript:myCode();>执行< / a> 

方法3:

 < a href =javascript:void(0);的onclick = mycode的(); >执行< / A> 

方法4(不像我认为的其他语言那样愉快):

 < span id =executeMyCodeLinkclass =link>执行< / a> 
< script>
$('#executeMyCodeLink')。click(myCode);
< / script>

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

解决方案


$ b使页面不会跳转,并使用带有href的方法4和使用preventDefault的方法4。 $ b

 < a id =executeMyCodeLinkhref =#>执行< / a> 
< script>
$('#executeMyCodeLink')。click(function(event){
event.preventDefault();
myCode();
});
< / script>

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


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?

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

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

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

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

method 3:

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

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

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

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

解决方案

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>

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

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

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