Prefered way to display anchors that don't need an href?
What is the preferred way to display an anchor that doesn't need an href attribute (because it's only used in javascript)?
For example, <a href="#">example 1</a>
vs. &开发者_开发百科lt;a href="javascript:;">example 2</a>
.
You should always set a fallback link for users without Javascript. When calling the javascript, you can return false from the handler to avoid the link activating. For example:
<a href="page.html" onclick="doSomething(); return false;">example 1</a>
The alternative, if there is no appropriate page to link to, is to not use a link at all. Use a button instead. You could style it to look like your links if that's really necessary.
Ideally the href should do something as close as possible to what the javascript was going to do.
For example, if the Javascript was going to pop-up a lightbox with a larger picture, the href should take you to a new page where you can see the same bigger picture.
If you take this approach, people without javascript still get a good experience and people with javascript get an smoother, glossier experience.
Check out Unobtrusive JavaScript and Progressive enhancement
As mentioned by other users, if a non javascript fallback is possible than use that as your href.
Example of opening an image in a popup for users with javascript, while falling back to a regular page load for users without (using jQuery):
<a class="popup" href="path/to/image.png">Baby Llama Picture</a>
<script>
// Assuming a function called popUpImage does the magic
$('.popup').click(function(event) {
popUpImage($(this).attr('href'));
event.preventDefault();
});
</script>
Any links that have no useful defined behaviour without javascript should be injected into the page using javascript. This way users without javascript will never see them, and there is no need to provide a valid href.
Example of inserting javascript only links dynamically (using jQuery):
<img class="editable" src="baby-llama.png" />
<script>
// Assuming a function doEditing that allows javascript based editing of an image
$(function() {
$('.editable').each(function() {
var editable = $(this);
var editLink = $('<a href="">Edit image</a>');
editLink.click(function() {
doEditing(editable);
});
editable.insertAfter(editLink);
});
});
</script>
you should stick to what rikh and DisgruntledGoat mentioned to make your site usable for peaple withou javascript.
if you want to do something that isn't needed or possible without javascript, you should use <a href="#">example 1</a>
and let you onclick-funktion return false
to prevent jumping to the top of the page - but the best way is always a "normal" link as fallback.
精彩评论