使用Javascript将UTM参数传递给按钮URL

时间:2019-02-25 16:22:25

标签: javascript for-loop

这里我有一个代码,该代码应该在url中使用utm参数,并将其传递给具有特定href域的所有按钮。但是,此代码在第12行字符27(这是带有for循环的行)上运行了编译错误,我不明白为什么。有人可以帮忙吗? 谢谢

<script type="text/javascript">

(function() {
var utmInheritingDomain = "https://www.motorstore.com/amr_en/checkout/", 
utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
links = document.getElementsByTagName("a"),
utms = [
"utm_medium={{utm_medium}}", 
"utm_source={{utm_source}}", 
"utm_campaign={{utm_campaign}}", 
];

for (var index = 0; index 0) { 
tempLink = tempLink.replace(utmRegExp, "");

tempParts = tempLink.split("#");

if (tempParts[0].indexOf("?") < 0 ) {
tempParts[0] += "?" + utms.join("&"); 
} else {
tempParts[0] += "&" + utms.join("&");
}

tempLink = tempParts.join("#");
}

links[index].href = tempLink;
}
}());

</script>

2 个答案:

答案 0 :(得分:0)

似乎您的}过多,并且for循环无效

(function() {
    var utmInheritingDomain = "https://www.motorstore.com/amr_en/checkout/", 
    utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
    links = document.getElementsByTagName("a"),
    utms = [
        "utm_medium={{utm_medium}}", 
        "utm_source={{utm_source}}", 
        "utm_campaign={{utm_campaign}}", 
    ];

    // Invalid for loop
    // for (var index = 0; index 0) {
    for (var index = 0; index < links.length; index++ 
        tempLink = tempLink.replace(utmRegExp, "");

        tempParts = tempLink.split("#");

        if (tempParts[0].indexOf("?") < 0 ) {
            tempParts[0] += "?" + utms.join("&"); 
        } else {
            tempParts[0] += "&" + utms.join("&");
        }

        tempLink = tempParts.join("#");
    }

    links[index].href = tempLink;
    // } <- this one
}());

您的tempLinktempParts变量也没有在任何地方定义。

答案 1 :(得分:0)

您希望它说类似

for (var index = 0; index < links.length; index++) {