Uncaught SyntaxError: Unexpected token if

I create a WordPress ShortCode tab and write this code to collect the short code

jQuery('body').on('click', '#tapSubmit',function(){ var shortcode = '[tapWrap]'; jQuery('.tapForm').each(function(){ var title = jQuery('.Title').val(), content = jQuery('.Content').val(), shortcode += '[tap '; if(title){shortcode += 'title="'+title+'"';} shortcode += ']'; if(content){shortcode += ''+content+'';} shortcode += '[/tap]'; }); shortcode += '[/tapWrap]'; tinyMCE.activeEditor.execCommand('mceInsertContent', false, shortcode); }); 

and i get this error

 Uncaught SyntaxError: Unexpected token if 

and I try the code at http://jsfiddle.net/ and I got this error in the line that has this code

 shortcode += '[tap '; Expected an assignment or function call and instead saw an expression. 

how to fix it?

+4
source share
2 answers

If you

 var title = jQuery('.Title').val(), content = jQuery('.Content').val(), shortcode += '[tap '; 

you define new variables in this chain, but shortcode already defined, so you create a new variable in this scope. Being a new variable, you cannot use += . Anyway, I think you just want to use this:

 var title = jQuery('.Title').val(), content = jQuery('.Content').val(); // changed the last comma with semicolon shortcode += '[tap '; 

To read:
About area
About var

+4
source

The problem is here.

 var title = jQuery('.Title').val(), content = jQuery('.Content').val(), shortcode += '[tap '; 

shortcode already the var defined above. You cannot use += in a var statement

Just change it to

 var title = jQuery('.Title').val(), content = jQuery('.Content').val(); // note the semicolon here shortcode += '[tap '; 

I think you will also face the problem of nesting. Instead of calling jQuery('.Content').val() for each iteration of the loop, I think you are looking for something like $(this).find('.Content').val() or $('.Content', this) This will find the corresponding .Content entry in the scope of the specified .tapForm .

I think about it, but it's just an idea.

 jQuery('body').on('click', '#tapSubmit', function(){ function title(context) { var value = jQuery(".Title", context).val(); return value ? 'title="' + value + '"' : ''; } function content(context) { var value = jQuery(".Content", context).val(); return value || ''; } var taps = jQuery('.tapForm').map(function(){ return '[tap ' + title(this) + ']' + content(this) + '[/tap]'; }).join(); tinyMCE.activeEditor.execCommand('mceInsertContent', false, '[tapWrap]' + taps + '[/tapWrap]'); }); 
+3
source

Source: https://habr.com/ru/post/1499027/


All Articles