2017-08-15 70 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