将 URL 参数从一个页面传递到另一个页面

Sal*_*l B 2 javascript jquery

尝试执行以下操作:

存储来自 url 的参数,ig mydomain.com/page.html?cid=123456

如果用户点击一个按钮(他们有一个 .btn-cta 类),它将获取参数 ?cid=123456 并将它们添加到新页面,这些按钮链接到 /tour.html

我目前正在通过将参数传递给页面上的 iframe 来完成其中的 1/2,现在我需要让上述部分工作:

var loc = window.location.toString(),  
    params = loc.split('?')[1],  
    iframe = document.getElementById("signupIndex"),
    btn = $('.btn-cta');  

iframe.src = iframe.src + '?' + params;
Run Code Online (Sandbox Code Playgroud)

Pat*_*son 5

下面是我如何使用 jquery 做到这一点:

     $('.btn-cta').each(function(i, el){
        let $this = $(this); // only need to create the object once
        $this.attr({
            href: $this.attr("href") + window.location.search
        });
    });
Run Code Online (Sandbox Code Playgroud)

在香草 ES2015 中

    document.querySelectorAll('.btn-cta')
        .forEach(el => el.attributes.href.value += window.location.search);
Run Code Online (Sandbox Code Playgroud)

这需要所有具有类的元素.btn-cta并将页面查询字符串附加到它们的每个href属性。

所以如果页面 url 是 ` http://domain/page.html?cid=1234

<a href="/tour.html" class="btn-cta">Tour</a>
Run Code Online (Sandbox Code Playgroud)

变成

<a href="/tour.html?cid=1234" class="btn-cta">Tour</a>
Run Code Online (Sandbox Code Playgroud)