将URL参数添加到文档jquery中的链接

时间:2015-09-24 12:13:25

标签: javascript jquery url parameters

我遇到了麻烦,从链接抓取参数并将它们附加到链接的末尾。我可以更改元素的文本但不能更改属性。看我的不工作的例子。

$(document).ready(function() {
            var urlParams = window.location.search;
            if (urlParams) {
                // remove leading '?' if present
                var cleanUrlParams = (urlParams[0]=='?') ? urlParams.substring(1, urlParams.length) : urlParams;

                // remove leading and trailing '&' if present
                var cleanUrlParams = (cleanUrlParams[0]=='&') ? cleanUrlParams.substring(1, cleanUrlParams.length) : cleanUrlParams;
                var cleanUrlParams = (cleanUrlParams[cleanUrlParams.length - 1]=='&') ? cleanUrlParams.substring(0, cleanUrlParams.length - 1) : cleanUrlParams;

                // include only the url params with values
                var includeUrlParams = "";
                var urlParamPairs = cleanUrlParams.split("&");
                for (var i = 0; i < urlParamPairs.length; i++) {
                    var splitUrlParamPair = urlParamPairs[i].split("=");
                    if ((splitUrlParamPair.length == 2) && (splitUrlParamPair[1].length > 0)) {
                        if (includeUrlParams.length > 0) {
                            includeUrlParams = includeUrlParams + "&";
                        }
                        includeUrlParams = includeUrlParams + urlParamPairs[i];
                    }
                }

                // if there are url parameters then append them to something in the DOM
                if (includeUrlParams.length > 0) {
                    $(".editMyUrlParams").attr("href" + includeUrlParams);
                }
            }
        });

然后像这样称呼它

<a class="editMyUrlParams" href="http://thisisawebsite.com/">This is a link</a>

我认为这是我出错的地方。如果我将以下内容更改为文本 - 它可以正常工作

if (includeUrlParams.length > 0) {
                    $(".editMyUrlParams").text("There are the params: " + includeUrlParams);
                }

所以我知道我错过了一些可以将属性附加到href末尾并获得这样结果的内容

<a class="editMyUrlParams" href="http://thisisawebsite.com/?param1=this1&param2=this2">This is a link</a>

提前感谢您提供任何帮助

1 个答案:

答案 0 :(得分:2)

使用jQuery .attr()方法:

$(".editMyUrlParams").attr('href', $(".editMyUrlParams").attr('href') + stringToAppend);

或更好:

var $elements = $(".editMyUrlParams");
var oldHrefValue = $elements.attr('href');
var newHrefValue = oldHrefValue + stringToAppend;
$elements.attr('href', newHrefValue);