Proper way for links to execute javascript code(链接执行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代码的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:链接执行javascript代码的正确方法


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01