单击按钮时转到链接 - 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
go to link on button click - jquery
提问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.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
首先,使用window.location
更好,因为根据规范document.location
值是只读的,可能会导致您在旧版/不同浏览器中头疼。检查注释@ MDC DOM document.location 页面
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.
对于第二个 - 使用attr
jQuery 方法获取 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.href
but 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