End*_*ssa 194
不引人注目的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>
Run Code Online (Sandbox Code Playgroud)
Che*_*sea 178
<a onclick="jsfunction()" href="#">
Run Code Online (Sandbox Code Playgroud)
要么
<a onclick="jsfunction()" href="javascript:void(0);">
Run Code Online (Sandbox Code Playgroud)
编辑:
上面的回答确实不是一个好的解决方案,自从我最初发布以来已经学到了很多关于JS的知识.有关解决此问题的更好方法,请参阅下面的EndangeredMassa答案.
Mat*_*nde 42
<a href="javascript:alert('Hello!');">Clicky</a>
Run Code Online (Sandbox Code Playgroud)
编辑,多年后:不!不要这样做!我当时年少无知!
Mis*_*cky 42
而且,为什么不用jQuery不引人注目:
$(function() {
$("#unobtrusive").click(function(e) {
e.preventDefault(); // if desired...
// other methods to call...
});
});
Run Code Online (Sandbox Code Playgroud)
HTML
<a id="unobtrusive" href="http://jquery.com">jquery</a>
Run Code Online (Sandbox Code Playgroud)
Fir*_*row 10
不引人注目的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;
}
}
}
Run Code Online (Sandbox Code Playgroud)如果javascript成功运行,可能使用javascript加载当前页面中的内容,返回false会取消链接触发.换句话说,如果javascript成功运行,put 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>
Run Code Online (Sandbox Code Playgroud)