单击按钮时转到链接 - jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4944387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:14:19  来源:igfitidea点击:

go to link on button click - jquery

jquerydynamic-dataresponse.redirect

提问by blasteralfred Ψ

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".

button1 具有可变的唯一 ID。单击时,页面必须重定向到 url“ www.example.com/index.php?id=buttonid”,但现在页面仅重定向到“ button id”。

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

我想www.example.com/index.php?id=在当前 url 之前添加字符串“ ”。我怎样才能做到这一点?

回答by Tom Tu

$('.button1').click(function() {
   window.location = "www.example.com/index.php?id=" + this.id;
});

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

首先,使用window.location更好,因为根据规范document.location值是只读的,可能会导致您在旧版/不同浏览器中头疼。检查注释@ MDC DOM document.location 页面

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

对于第二个 - 使用attrjQuery 方法获取 id 是一种不好的做法 - 您应该使用直接本机 DOM 访问器,this.id因为分配给的值this是普通 DOM 元素。

回答by Sarfraz

You need to specify the domain:

您需要指定域:

 $('.button1').click(function() {
   window.location = 'www.example.com/index.php?id=' + this.id;
 });

回答by bobgubko

$('.button1').click(function() {
   document.location.href='/index.php?id=' + $(this).attr('id');
});

回答by Chowlett

Why not just change the second line to

为什么不把第二行改为

document.location.href="www.example.com/index.php?id=" + $(this).attr('id');

回答by Guillaume86

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

您可以获得当前的 url,window.location.href但我认为您将需要 jQuery 查询插件来操作查询字符串:http: //plugins.jquery.com/project/query-object