简体   繁体   English

将变量添加到href URL的末尾onClick JQUERY

[英]Add variable to end of href URL onClick JQUERY

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>

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. 其次,在你的代码中“this”指的是窗口,而不是元素。 Try this instead: 试试这个:

<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';
    });
}

Why don't you add an ID or Class to your link href to identify it through jquery? 为什么不在链接href中添加ID或类以通过jquery识别它? It seems like your link is triggered before you can add any data to href attribute. 在将任何数据添加到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>
     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'
           }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM