Append Query String From Variable To Every URL

时间:2015-04-24 21:29:50

标签: javascript append query-string

I created a query string and appended it to the URL like so:

// HTML from index.html
<input type="button" value="Yes" onclick="redirect(this);" id="YES" class="btn btn-primary btn-lg">
<input type="button" value="No" onclick="redirect(this);" id="NO" class="btn btn-primary btn-lg">
// JS on index.html
function redirect(e){

    var mapPg = "map.html";
    var qString = "?choice=";
    location.href = mapPg + qString + e.id;

}

Beginning on the map.html page, I want to take that query string and carry it through to every URL, except the index.html page.

When the user clicks on price.html pg, it'll use the query string to call a function that will pull in the data for the "yes" answer. Same thing goes for the "no" answer.

I can't figure out how to append the query string to the URL of every pg on click.

The nav is a JavaScript include that's been pulled in. I've added a class of qString to all the<a> in the nav in case it would be easier to target them.

3 个答案:

答案 0 :(得分:1)

jQuery是一个选项吗?如果是的话......

<script type="text/javascript">
$(document).ready(function() {
    $("a").prop("href", function() { return this.href + location.search; })
});
</script>

答案 1 :(得分:0)

您可以将其添加到每个页面:

window.addEventHandler("load", function() {
    var match = location.search.match(/\bchoice=([^&]*)/);
    if (!match) {
        return;
    }
    var choice = match[1];
    var navlinks = document.getElementsByClassName("qString");
    for (var i = 0; i < navlinks.length; i++) {
        if (navlinks[i].search == '') {
            navlinks[i].search = '?choice=' + choice;
        } else {
            navlinks[i].search += '&choice=' + choice;
        }
    }
}

答案 2 :(得分:0)

location.href = mapPg + qString + e.id;

此处的代码需要更改。 e.getAttribute(&#34; ID&#34)