正确的方式来执行JavaScript代码的链接 [英] Proper way for links to execute javascript code
问题描述
方法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屋!