为什么每次单击空链接时都会引用我的页面

Why my page is refresed every time I click a empty link?

本文关键字:引用 我的 单击 链接 为什么      更新时间:2023-09-26

我有一个这样的链接:

<a hreflang="15" class="comment-show-link" href="">View/hide comments</a>

然后让这段代码显示/隐藏内容:

$('.comment-show-link').click(function(e) {
  $('#comment-show-'+$(this).attr("hreflang")).slideToggle('slow');
  e.stopPropagation();
});

但是当我单击链接时,页面被发送并且没有显示div"#comment-show-",为什么?我做错了什么?

你不需要stopPropagation(这会阻止事件冒泡),你想要preventDefault(这会阻止事件 的默认操作 - 在这种情况下,点击链接)。或者只是从事件处理程序函数返回false(它同时执行[在链接上,向下滚动到以"返回false..."开头的段落])。

尝试:

<a data-hreflang="15" class="comment-show-link" href="#">View/hide comments</a>

-

$('.comment-show-link').on('click', function(e) {
    e.preventDefault();
    $('#comment-show-'+$(this).data("hreflang")).slideToggle('slow');
});

或者为了防止默认操作和冒泡,请执行

$('.comment-show-link').on('click', function() {
    $('#comment-show-'+$(this).data("hreflang")).slideToggle('slow');
    return false;
});

只需传递给href属性javascript:;

<a hreflang="15" class="comment-show-link" href="javascript:;">View/hide comments</a>

这是锚标记的行为。我想你想让e.PreventDefault阻止它。

删除 href,它是没有用的(当然最好使用简单的跨度)。

如果添加它来更改光标,请改用 css (cursor:pointer)。

您可以使用preventDefault() ;

$('.comment-show-link').click(function(e) {
  $('#comment-show-'+$(this).attr("hreflang")).slideToggle('slow');
  e.preventDefault();
});

不要使用链接。

您没有链接到任何内容,因此将您的内容标记为链接是没有意义的。

尝试

$('.comment-show-link').click(function(e) {
  $('#comment-show-'+$(this).attr("hreflang")).slideToggle('slow');
  e.stopPropagation();
  return false;
});

尝试将 href 属性设置为 href="javascript:void(0);"

这是一个jsfiddle:

http://jsfiddle.net/septerr/taCvq/