将URL参数传递到表单的隐藏字段中

时间:2018-06-22 15:35:40

标签: javascript

我正在使用以下脚本(实际上是从博客获得的)将utm_campaign和utm_source之类的URL参数传递给表单中的隐藏字段。但是该脚本未执行,并且在浏览器控制台中显示错误。但是我不是开发人员,所以我真的不知道该如何解决:(

这是代码:

<script>
// Parse the URL to get the required field values

function getUtmParamByName(utmname) {

    utmname = utmname.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 source = getUtmParamByName('utm_source');
var medium = getUtmParamByName('utm_medium');
var campaign = getUtmParamByName('utm_campaign');
var content = getUtmParamByName('utm_content');
var term = getUtmParamByName('utm_term');
// Put the variable names into the hidden fields in the form.
$( document ).ready(function() {
    $('#form-field-utm_source').val(source);
    $('#form-field-utm_medium').val(medium);
    $('#form-field-utm_campaign').val(campaign);
    $('#form-field-utm_content').val(content);
    $('#form-field-utm_term').val(term);
}
</script>

请帮助!

TIA

2 个答案:

答案 0 :(得分:0)

在首页部分添加对jQuery库的引用

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

我整理了!代替:

$( document ).ready(function() {

我将其更改为:

$(function() {