以下问题,我希望在隐藏字段中填写UTM参数。但是不起作用。我不熟悉javascript,但所有其他领域只有utm才会产生问题。这是带参数的URL
myurl.com?utm_source=facebook&utm_medium=twitter&utm_campaign=google
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var campaign = getParameterByName('utm_campaign');
// Put the variable names into the hidden fields in the form.
document.getElementsByName("ck_field_utm_campaign").value = campaign;

<input type="hidden" value="" name="ck_field_utm_campaign" class="ck_field_utm_campaign" id="ck_field_utm_campaign">
&#13;
答案 0 :(得分:1)
document.getElementsByTagName
返回一个数组。 (元素标签名称)
所以当你写:
document.getElementsByName("ck_field_utm_campaign").value = campaign;
您基本上将.value
属性分配给函数返回的数组。而是使用.querySelector
(返回单个元素或null)或访问getElementsByName返回的数组中的第一个项目,并为其指定.value
。
使用querySelector:
document.querySelector("[name='ck_field_utm_campaign']").value = campaign;
访问第一项:
var input = document.getElementsByName("ck_field_utm_campaign");
// input now contains an ARRAY of elements that match that name
// but if you're sure that only one input has that name you can easily access
// that input
input = input[0];
input.value = campaign;