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代码的正确方法


基础教程推荐
- npm start 错误与 create-react-app 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01