How to prevent page refresh when tag clicked?

2020-04-18 06:07发布

I need to pass a parameter into the URL and at the same time prevent page from reloading when I click any <a> tag with a blank href attribute (<a href="">)

Is there a way to do this with JS/jQuery?

I have this jQuery already

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

But when I click <a href="inbox/1">Message</a> (any anchor with an href) preventDefault stops that value from being passed into the url.

Can anyone help?

Thanks in advance.

4条回答
时光不老,我们不散
2楼-- · 2020-04-18 06:12

window.location.hash="inbox/1" can update the hash value in the url. This can be done with the event preventDefault code.

查看更多
对你真心纯属浪费
3楼-- · 2020-04-18 06:21

You can use Attribute equal selector to prevent click event in case of blank href like,

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

And I would like to suggest don't make empty the href's, you can place # if no links are there.

查看更多
男人必须洒脱
4楼-- · 2020-04-18 06:28

Try the following code

  $('.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
 });

For More details http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/

查看更多
迷人小祖宗
5楼-- · 2020-04-18 06:34

Use jQuery's fancy selectors, especially the attribute equals one.

Using it, you can select only <a> tags which have a blank href attribute:

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

The $('.list-group-item a[href=""]') selector narrows the collected elements to only those anchor tags with a class of list-group-item and a blank href.

That means all other anchor tags will work fine.

查看更多
登录 后发表回答