简体   繁体   中英

jQuery error on Custom Javascript variable in Google tag manager

Why am I getting an error when I run a jquery as a Custom javasript variable? The error description is "Error at line 10, character 2: Parse error. ')' expected"

function(){
  $( document ).ready(function() {
    $('button[class="panel__link panel__link--btb"]').on( 'click', function(e) {
       var $label = $( this ).parent().find("h2").text();
       return $label;
    });

  });
};

Please advise.

Regards,

Sree

Remove the last semicolon ; on the last line:

function(){
$( document ).ready(function() {
$('button[class="panel__link panel__link--btb"]').on( 'click', function(e) {
 var $label = $( this ).parent().find("h2").text();
return $label;
});

});
}

I think you did some conceptual mistake, when you working with GTM. Custom variable should return some value when trigger is fired.

I think your initial goal in GTM is:

Send some tag (to Universal analytics or something else) when user clicks on button button[class="panel__link panel__link--btb"] . This tag should contain some text information, which you can find like that .parent().find("h2").text();

If i am correct, then you should do the following:

  1. Go to Variables. Built-in variables-> Configure-> Enable Click Element
  2. Go to Triggers -> New -> Type: All Elements -> Click Element : matches CSS selector : button.panel__link.panel__link--btb
  3. Go to Variables. New -> Custom JavaScript: function(){return {{Click Element}}.parent().find("h2").text();} -> Name: 'H2 text'
  4. Go to Tags. New -> Assign trigger from step #2. -> Type: (you can choose what you need) -> And here you can use your variable {{H2 text}} , it will return necessary text

The error is caused because there no name for the function. I think you are trying to do a Self Invoking function which should be

(function(){
   //your code
}());

Your code should be,

(function(){
  $( document ).ready(function() {
    $('button[class="panel__link panel__link--btb"]').on( 'click', function(e) {
      var $label = $( this ).parent().find("h2").text();
      return $label;
    });

  });
}());

Or

Remove the function() {} and simply execute the code with .ready

$( document ).ready(function() {
    $('button[class="panel__link panel__link--btb"]').on( 'click', function(e) {
      var $label = $( this ).parent().find("h2").text();
      return $label;
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM