最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to prevent page refresh when <a> tag clicked? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jan 5, 2015 at 12:45 Michel asked Jan 5, 2015 at 11:26 MichelMichel 1,1651 gold badge10 silver badges25 bronze badges 3
  • 2 It's not very clear what you're trying to say? What exactly do you wanna do with the value? – user1248084 Commented Jan 5, 2015 at 11:28
  • I think he need to change the url without redirect – Shijin TR Commented Jan 5, 2015 at 11:48
  • I need to change the URL without redirect as Shijin said. – Michel Commented Jan 5, 2015 at 11:54
Add a ment  | 

4 Answers 4

Reset to default 1

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

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./blog/html5-changing-the-browser-url-without-refreshing-page/

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.

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.

发布评论

评论列表(0)

  1. 暂无评论