href="javascript:void(0)" vs. advanced disabling of links
I use
href="开发者_JAVA百科javascript:void(0)"
to disable the href property and then use onlclick to give functionality to my anchor elements. How can I do this programatically.
A few issues if I may.
I would suggest an unobtrusive approach
I would not use return false. It could have unexpected results. A quick google search will have more info.
Use preventDefault() to remove the default functionality.
https://developer.mozilla.org/en/DOM/event.preventDefault
Edit:
If you're unsure how to control the click event unobtrusively, addEventListener() is what you are after. You can control everything from there, including preventDefault() https://developer.mozilla.org/en/DOM/element.addEventListener
Not sure what you mean when you say "works in xhtml, but not in javascript."
If you want to disable a link you can just use return false to cancel the default action.
<a href="http://www.apple.com" onclick="return false;">Apple</a>
Update - in context of a function
<a href="/mypage.html" onclick="myFunction();">My Page</a>
<a href="/mypage.html" onclick="myFunction2(); return false;">My Page</a>
<script>
function myFunction() {
//do all the javascript stuff i want
return false;
}
function myFunction2() {
//do all the javascript stuff i want
}
</script>
Don't put javascript in href. Leave the href alone. Do what you want in onclick, just make sure it returns false (so that default link action isn't executed). And remember that people opening the link in new tab/window won't get your code executed - they'll just open the link under href.
If it doesn't make sense to have a href at all, you can also have onclick on any other element, not just a.
精彩评论