go to link on button click - jquery

2019-03-09 08:28发布

I have a script as below

$('.button1').click(function() {
    document.location.href=$(this).attr('id');
});

the button1 has variable unique ids. on click, the page must redirect to url "www.example.com/index.php?id=buttonid" but now the page is redirecting only to "button id".

I want to add the string "www.example.com/index.php?id=" before the current url. How can I make this possible?

5条回答
一夜七次
2楼-- · 2019-03-09 09:15

You need to specify the domain:

 $('.button1').click(function() {
   window.location = 'www.example.com/index.php?id=' + this.id;
 });
查看更多
可以哭但决不认输i
3楼-- · 2019-03-09 09:17

Why not just change the second line to

document.location.href="www.example.com/index.php?id=" + $(this).attr('id');
查看更多
够拽才男人
4楼-- · 2019-03-09 09:19
$('.button1').click(function() {
   window.location = "www.example.com/index.php?id=" + this.id;
});

First of all using window.location is better as according to specification document.location value was read-only and might cause you headaches in older/different browsers. Check notes @MDC DOM document.location page

And for the second - using attr jQuery method to get id is a bad practice - you should use direct native DOM accessor this.id as the value assigned to this is normal DOM element.

查看更多
来,给爷笑一个
5楼-- · 2019-03-09 09:22
$('.button1').click(function() {
   document.location.href='/index.php?id=' + $(this).attr('id');
});
查看更多
男人必须洒脱
6楼-- · 2019-03-09 09:22

you can get the current url with window.location.href but I think you will need the jQuery query plugin to manipulate the query string: http://plugins.jquery.com/project/query-object

查看更多
登录 后发表回答