Answers:
<a onclick="jsfunction()" href="#">
要么
<a onclick="jsfunction()" href="javascript:void(0);">
编辑:
上面的回答确实不是一个好的解决方案,自从我最初发布以来,已经学到了很多有关JS的知识。有关解决此问题的更好方法,请参见下面的EndangeredMassa答案。
简洁的JavaScript,无库依赖:
<html>
<head>
<script type="text/javascript">
// Wait for the page to load first
window.onload = function() {
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function() {
// Your code here...
//If you don't want the link to actually
// redirect the browser to another page,
// "google.com" in our example here, then
// return false at the end of this block.
// Note that this also prevents event bubbling,
// which is probably what we want here, but won't
// always be the case.
return false;
}
}
</script>
</head>
<body>
<a id="mylink" href="http://www.google.com">linky</a>
</body>
</html>
href
如果我不想重定向用户而只想运行一些代码,该怎么办?编辑:我看到它可以留为空白:href=""
。
onclick
通过通过添加事件window.onload
,而不是onclick
直接将其放入<a>
代码?
<a href="javascript:alert('Hello!');">Clicky</a>
多年后编辑:不!永远不要这样做!我当时年少无知!
再次编辑:几个人问您为什么不应该这样做。有两个原因:
演示文稿: HTML应该专注于演示文稿。将JS放在HREF中意味着您的HTML现在正在处理业务逻辑。
安全性: HTML中的Javascript违反了内容安全策略(CSP)。内容安全策略(CSP)是安全性的附加层,有助于检测和缓解某些类型的攻击,包括跨站点脚本(XSS)和数据注入攻击。这些攻击可用于从数据盗窃到站点损坏或恶意软件分发的所有方面。在这里阅读更多。
可访问性:锚标记用于链接到其他文档/页面/资源。如果您的链接没有到任何地方,则应为一个按钮。这样,屏幕阅读器,盲文终端等就可以轻松确定发生了什么,并为视障用户提供有用的信息。
href='#'
和alert()
在onclick
?
而且,为什么不让jQuery变得不引人注目:
$(function() {
$("#unobtrusive").click(function(e) {
e.preventDefault(); // if desired...
// other methods to call...
});
});
的HTML
<a id="unobtrusive" href="http://jquery.com">jquery</a>
不打扰的Javascript有很多优点,这是它采取的步骤以及为什么要好用。
链接正常加载:
<a id="DaLink" href="http://host/toAnewPage.html">点击此处</a>
这很重要,因为它适用于未启用javascript的浏览器,或者javascript代码中的错误不起作用。
javascript在页面加载时运行:
window.onload = function(){
document.getElementById("DaLink").onclick = function(){
if(funcitonToCall()){
// most important step in this whole process
return false;
}
}
}
如果javascript成功运行,也许使用javascript加载了当前页面中的内容,则返回false将取消链接触发。换句话说,如果javascript成功运行,则将return false设置为禁用链接的效果。如果javascript不允许运行它,则可以做一个很好的备份,以便您的内容以任何一种方式显示,对于搜索引擎来说,如果您的代码中断了,或者可以在非JavaScript系统上查看。
关于这个主题的最好的书是杰里米·基思(Jeremy Keith)的“ Dom Scription”
或者,如果您使用的是PrototypeJS
<script type="text/javascript>
Event.observe( $('thelink'), 'click', function(event) {
//do stuff
Event.stop(event);
}
</script>
<a href="#" id="thelink">This is the link</a>
基于@mister_lucky答案与jquery一起使用:
$('#unobtrusive').on('click',function (e) {
e.preventDefault(); //optional
//some code
});
HTML代码:
<a id="unobtrusive" href="http://jquery.com">jquery</a>
只需使用javascript:----示例
javascript:var JFL_81371678974472 = new JotformFeedback({ formId: '81371678974472', base: 'https://form.jotform.me/', windowTitle: 'Photobook Series', background: '#e44c2a', fontColor: '#FFFFFF', type: 'false', height: 700, width: 500, openOnLoad: true })