2017-08-15 72 views
0

我正在使用JavaScript创建将发布utm_source value =“”的cookie。JavaScript Cookie - 未通过utm_source值的表单

在我看到utm_source值控制台,但不是在表格上

// 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 source = getParameterByName('utm_source'); 

    // Set the cookies 
    if(Cookies.set('utm_source') == null || Cookies.set('utm_source') == "") { 
     Cookies.set('utm_source', source); 
    } 

    // Grab the cookie value and set the form field values 
    $(document).ready(function(){ 
     $('input[name=utm_source').val(utm_source); 
    }); 

</script> 
+0

您的Cookie变量来自哪里?如果您正在使用图书馆,请提供一个链接。此外,在这一行上:'$('input [name = utm_source').val(utm_source);',你缺少一个右括号,并且你正在使用'utm_source'变量,这个变量在您发布的代码段。你的意思是代替'source'吗?最后,在你最后一块“抓取cookie值并设置......”时,你根本没有使用cookies。 – blex

+0

我从jQuery起诉以下内容。 https://github.com/js-cookie/js-cookie https://code.jquery.com/jquery-latest.min.js – Noel

回答

0

问题1

$('input[name=utm_source').val(utm_source); 

上述线导致的问题原因有两个:

  • 你缺少一个右括号
  • utm_source不被任何定义(在您发布的片断)

如果你想使用的cookie的值,你应该这样做:

$('input[name=utm_source]').val(Cookies.get('utm_source')); 

习题LEM 2

在此行中:

if(Cookies.set('utm_source') == null || Cookies.set('utm_source') == "") { 

我认为你错误地使用.get(),它可以简化成这样.set()代替:

if(!Cookies.get('utm_source')) { 

这会工作,因为null""都是谬误值。

+0

我用你推荐的源代码,但它没有工作。 – Noel

+0

Noel

+0

我在控制台上看到value =“”,但在源代码中看不到。感谢您的帮助。 – Noel

0

谢谢你们!得到它的工作!必须替换名称= customID