【问题标题】:Error with embedding moment.js嵌入 moment.js 时出错
【发布时间】:2017-04-05 00:34:10
【问题描述】:

我在浏览器代码中包含 moment.js 时遇到了困难。这是我第一次使用它并自学使用图书馆,因此感谢您的帮助。我的 html 页面中有一个 CDN:

      <!-- jQuery cdn -->
    <script src="http://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

      <!-- moment.js cdn -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/locale/af.js"></script>

      <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <script src="script.js"></script>
    <script type="text/javascript">
      var momentTest = moment(); 
      console.log(momentTest);  // this is not logging
    </script>

同样在我的 script.js 文件中,我尝试使用 format() 以另一种方式调用它,就像我在文档中看到的那样:

 var now = moment().format();
 console.log(now); //this is not logging either

但我不断收到控制台错误 - Uncaught ReferenceError: moment is not defined。有人能帮忙吗?我已经看过这篇文章,但对我没有帮助(完全是初学者):How to use Moment.js?

【问题讨论】:

  • 看起来您可能暂时使用了错误的 cdn 地址。我尝试使用&lt;script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"&gt;&lt;/script&gt;,效果很好。你可以试试吗?

标签: javascript momentjs cdn


【解决方案1】:

此行不会加载 moment.js,但会加载 moment.js 的 af(南非荷兰语)语言环境。

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/locale/af.js"></script>

要加载 moment.js,您需要加载 moment.js 文件:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

【讨论】:

  • 非常感谢!我什至没有注意到哪个是正确的——只是选择了最上面的那个。再次感谢!
【解决方案2】:

试试这个:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<script src="script.js"></script>

    <script type="text/javascript">
      var momentTest = moment(); 
      console.log(momentTest);  // this is not logging
    </script>

【讨论】:

  • 不要将下载链接直接用作脚本。您应该改为使用诸如 CloudFlare 之类的 moment.js 链接到 CDN,因为这些服务专用于以这种方式提供脚本。
猜你喜欢
  • 2023-01-18
  • 1970-01-01
  • 2020-08-08
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
相关资源
最近更新 更多