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


基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01