如何在<a> tag clicked?</a>时阻止页面刷新

时间:2015-01-05 11:26:41

标签: javascript jquery html anchor

我需要将一个参数传递到网址中,同时当我点击任何<a>标记并使用空白href属性(<a href="">

有没有办法用JS / jQuery做到这一点?

我已经有了这个jQuery

$('.list-group-item a').click(function (event) {
  event.preventDefault();
});

但是当我点击<a href="inbox/1">Message</a>(任何带有href的锚点)时,preventDefault会阻止该值传递到网址。

有人可以帮忙吗?

提前致谢。

4 个答案:

答案 0 :(得分:1)

window.location.hash="inbox/1"可以更新网址中的哈希值。这可以使用事件preventDefault代码完成。

答案 1 :(得分:1)

尝试以下代码

  $('.list-group-item a').click(function (event) {
   event.preventDefault();
   var url = $(this).attr('href');
   window.history.replaceState("object or string", "Title",url); // this will change your url
 });

了解更多详情http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/

答案 2 :(得分:0)

您可以使用Attribute equal selector来阻止点击事件,例如空白href,

$('.list-group-item a[href=""]').click(function (event) { // where href are blank
   event.preventDefault();
});

我想建议不要将href's清空,如果没有链接,可以放置#

答案 3 :(得分:0)

使用jQuery&#39; fancy selectors,尤其是attribute equals

使用它,您只能选择具有空白href属性的<a>标记:

$('.list-group-item a[href=""]').click(function(event) {
  event.preventDefault();
});

$('.list-group-item a[href=""]')选择器将收集的元素缩小为仅具有list-group-item类和空白href的锚标记。

这意味着所有其他锚标签都能正常工作。

相关问题