【问题标题】:Uncaught SyntaxError: Unexpected token ifUncaught SyntaxError: Unexpected token if
【发布时间】:2013-08-26 20:11:02
【问题描述】:

我创建 WordPress ShortCode 选项卡并编写此代码来收集简码

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);
});

我得到这个错误

Uncaught SyntaxError: Unexpected token if 

我尝试了http://jsfiddle.net/ 中的代码,但在包含此代码的行中出现了此错误

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

如何解决?

【问题讨论】:

  • 从 var 定义链中删除这个 shortcode += '[tap ';。否则,您再次定义它,没有任何价值可添加。

标签: javascript jquery wordpress tinymce


【解决方案1】:

当你有

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

您正在该链中定义新变量,但 shortcode 已定义,因此您正在此范围内创建一个新变量。作为一个新变量,您不能使用+=。无论如何,我认为您只想使用它:

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

阅读:
关于scope
关于var

【讨论】:

    【解决方案2】:

    问题来了

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

    shortcode 已经是上面定义的 var。您不能在 var 表达式中使用 +=

    只需将其更改为

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

    我认为您还会遇到一些嵌套问题。我认为您不是在为循环的每次迭代调用jQuery('.Content').val(),而是在寻找更像$(this).find('.Content').val()$('.Content', this) 的东西。这将在给定的.tapForm 范围内找到相关的.Content 输入。

    我在想这样的事情,但这只是一个想法

    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]');  
    });
    

    【讨论】:

    • 我认为您应该强调第二个, 必须替换为;。仅查看代码可能并不明显。
    猜你喜欢
    • 1970-01-01
    • 2012-05-17
    • 2019-02-10
    • 2014-07-08
    • 2011-03-09
    • 2014-01-06
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多