什么是显示不需要href属性的锚点的首选方法(因为它仅在javascript中使用)?
例如,
例如,
<a href="#">example 1</a>
与<a href="javascript:;">example 2</a>
相比,哪一个更好?<a href="#">example 1</a>
与<a href="javascript:;">example 2</a>
相比,哪一个更好?对于没有启用Javascript的用户,您应该始终设置一个回退链接。在调用Javascript时,您可以从处理程序中返回false以避免链接激活。例如:
<a href="page.html" onclick="doSomething(); return false;">example 1</a>
正如其他用户所提到的,如果可以使用非JavaScript回退,则请使用href。
以下是一个示例,对于具有JavaScript的用户,在弹出窗口中打开图像,而对于没有JavaScript的用户则回退到常规页面加载(使用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>
<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>
你应该遵循Rikh和DisgruntledGoat提到的方法,使你的网站对没有JavaScript的人可用。
如果你想做一些没有JavaScript不需要或不可能实现的事情,你应该使用<a href="#">示例1</a>
,并让你的onclick函数return false
以防止跳转到页面顶部 - 但最好的方式始终是作为后备的“正常”链接。