如何使用链接调用JavaScript代码?
发布于 2009-03-27 01:38:35
<a onclick="jsfunction()" href="#">
或
<a onclick="jsfunction()" href="javascript:void(0);">
编辑:
上面的回答真的不是一个好的解决方案,因为我从最初的帖子中学到了很多关于JS的知识。有关解决此问题的更好方法,请参阅下面的EndangeredMassa's answer。
发布于 2009-03-27 01:50:53
不显眼的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>
发布于 2009-03-27 01:54:02
还有,为什么不用jQuery低调一点呢:
$(function() {
$("#unobtrusive").click(function(e) {
e.preventDefault(); // if desired...
// other methods to call...
});
});
HTML
<a id="unobtrusive" href="http://jquery.com">jquery</a>
https://stackoverflow.com/questions/688196
复制相似问题