问题
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?
method 1 (need to make sure myCode() returns false always):
<a href="#" onclick="return myCode();">execute</a>
method 2 (seems to make the most sense?):
<a href="javascript:myCode();">execute</a>
method 3:
<a href="javascript:void(0);" onclick="myCode();">execute</a>
method 4 (not as pleasant semantically as the others I think):
<span id="executeMyCodeLink" class="link">execute</a>
<script>
$('#executeMyCodeLink').click(myCode);
</script>
with method 4, you can use onclick as well of course..
回答1:
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>
It's important to include an href because links won't style properly and your html won't validate otherwise.
回答2:
I prefer method 4, but with two differences:
- Move the script to a separate file. Unobtrusive JavaScript is happy JavaScript.
- Use the a tag, link to # and return false.
回答3:
<a href="#_">
works too, that way you don't need a return false
. (Any non-existent anchor will work really).
Also, method 4 only works if you use jQuery. Most of my websites only have one or two small javascript effects, I'm not loading jQuery for that.
回答4:
Using jquery is an unobtrusive way to handle javascript calls. So I would say method 4. You can also just do:
$(a#linkId).click(...);
回答5:
I prefer method 4, too.
Binding events to dom objects seperately is a more elegant way and I think that's a good programming habit.
回答6:
I like method 4 as well. Whenever possible i try to not put anything directly in the even attributes or to write js directly into the href. I do this because in most cases ill actually put a non-js url as the href so it degrades for non-js enabled browsers. The second reson is i dont like to pollute elements with cruft :-)
来源:https://stackoverflow.com/questions/3668614/proper-way-for-links-to-execute-javascript-code