将变量添加到 href URL onClick JQUERY 的末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15652251/
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
Add variable to end of href URL onClick JQUERY
提问by 916 Networks
I feel like this should work, but doesn't. Not sure what I'm doing wrong.
我觉得这应该有效,但没有。不知道我做错了什么。
function addURL()
{
$(this).attr('href', function() {
return this.href + '&cylnders=12';
}
<a onclick="addURL();" href="/search-results/?var1=red&var2=leather">Click this</a>
回答by Christophe
First, you are missing a bunch of brackets:
首先,您缺少一堆括号:
function addURL()
{
$(this).attr('href', function() {
return this.href + '&cylnders=12';
});
}
Second, in your code "this" refers to the window, not the element. Try this instead:
其次,在您的代码中,“this”指的是窗口,而不是元素。试试这个:
<a onclick="addURL(this)" href="/search-results/?var1=red&var2=leather">Click this</a>
function addURL(element)
{
$(element).attr('href', function() {
return this.href + '&cylnders=12';
});
}
回答by luchosrock
Why don't you add an ID or Class to your link href to identify it through jquery? It seems like your link is triggered before you can add any data to href attribute.
你为什么不给你的链接 href 添加一个 ID 或 Class 来通过 jquery 来识别它呢?在您可以向 href 属性添加任何数据之前,您的链接似乎已被触发。
<a class="datalink" href="/search-results/?var1=red&var2=leather">Click this</a>
<script>
$('.datalink').attr('href', function() {
return this.href + '&cylnders=12';
});
</script>
回答by Nirmal
function addURL()
{
var data=window.location+"&cylnders=12";
alert(data);
}
Try this concept. hope it will give you some solution.
试试这个概念。希望它会给你一些解决方案。
Try this too
也试试这个
function addURL()
{
window.location.href='/search-results/?var1=red&var2=leather&cylnders=12'
}