【问题标题】:How to require jQuery Cookie using RequireJS in module definition?如何在模块定义中使用 RequireJS 来要求 jQuery Cookie?
【发布时间】:2013-12-31 17:58:26
【问题描述】:

我有以下依赖于 jQuery Cookie 的模块。如何将 $.cookie 或 jQuery.cookie 传入匿名函数?现在因为我没有传递任何东西,所以它在我的控制台中失败并显示以下错误消息:

Uncaught TypeError: Cannot call method 'cookie' of undefined

我的代码如下所示:

define(['//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js', '//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.3.1/jquery.cookie.min.js'], function($) {

  return function themeSwitcher(initTheme) {
    var body = document.body,
        main = document.querySelector('main'),
        activeTheme = body.classList,
        theme = document.querySelectorAll('.theme-switcher li');

    if ($.cookie('userTheme')) {
      $(body).removeClass(activeTheme[0])
      $(body).addClass($.cookie('userTheme'));
    } else {
      $(body).addClass(initTheme);
    }

    for (var i = 0; i < theme.length; i++) {
      theme[i].addEventListener('click', function(e) {
        var userTheme = e.target.className;

        if (!$.cookie('userTheme')) {
          $.cookie('userTheme', userTheme, { expires: 7, path: '/' });
          $(body).removeClass(activeTheme[0]);
          $(body).addClass($.cookie('userTheme'));
        } else {
          $.removeCookie('userTheme');
          $.cookie('userTheme', userTheme, { expires: 7, path: '/' });
          $(body).removeClass(activeTheme[0]);
          $(body).addClass($.cookie('userTheme'));
        }

      }, false);  

    }

  }

});

【问题讨论】:

  • 我不应该将任何东西传递给两个依赖项中的任何一个的匿名函数吗?

标签: javascript requirejs jquery-cookie


【解决方案1】:

jQuery cookie 从 1.4.0+ 版本开始支持 AMD。
你使用的1.3.1版本不支持。

【讨论】:

    猜你喜欢
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多