moment.js脚本无法切换为德语显示问题求助
解决Moment.js德语本地化不生效的问题
我来帮你排查下为什么德语locale没生效,一步步搞定:
1. 最关键的错误:选择器写错了
你代码里的$("clock").each(function()完全不对!你的时钟元素是带class="clock"的<div>,正确的类选择器应该是**$(".clock")**(必须加那个点)。选不到元素的话,后面的本地化代码根本跑不起来,自然还是默认显示英文。
2. 缺失时区库,导致Moment对象行为异常
你用了moment.tz()处理时区,但只加载了moment-with-locales.js——这个文件只包含语言包,没有时区数据!得额外加载带时区数据的moment-timezone库,不然时区转换会出问题,间接影响locale的生效。
3. 冗余的Locale设置,建议格式化时显式指定
你反复写moment.locale("de")其实没必要,全局设置一次就够。不过为了保险,在格式化日期的时候显式调用.locale('de'),避免时区转换过程中locale丢失。
修正后的完整代码
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script> <!-- 新增加载带时区数据的moment-timezone库 --> <script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.js"></script> <script> // 全局设置德语locale,一次就够 moment.locale("de"); function worldClock() { var now = moment(); // 修正选择器为.clock $(".clock").each(function() { var timezone = $(this).data('tz'); <%# we check the timezone to make sure it's valid %> if (moment.tz.zone(timezone)) { var tz_now = now.tz(timezone); // 格式化时显式指定locale,确保德语生效 $(this).html("<div class='date'>" + tz_now.locale("de").format('LL') + "</div>"); // 把重复的LL改成LT,显示时间而非重复日期 $(this).append("<div class='time'>" + tz_now.locale("de").format('LT') + "</div>"); $(this).append("<div class='time'>" + tz_now.locale() + "</div>"); $(this).append("<div class='time'>" + moment(1316116057189).locale('de').fromNow() + "</div>"); $(this).append("<div class='timezone'>" + timezone + "</div>"); } else { $(this).html("Unrecognized time zone " + timezone); } }); // 用函数引用代替字符串,避免作用域问题 setTimeout(worldClock, 1000); } $(function() { worldClock(); }); </script> <style> .clock { float: left; padding: 1em; text-align: center; } .time { font-size:1.4em; color:#005288; padding: 4px 0; } .timezone { font-size:1.1em; font-weight: 500; } </style> <div class="worldclock"> <%# Some other time zones: America/St_Johns Antarctica/Vostok Asia/Almaty Asia/Istanbul Asia/Novosibirsk %> <%# Asia/Samarkand Australia/Adelaide Australia/Adelaide Etc/GMT+9 Europe/Vilnius Asia/Ho_Chi_Minh %> <%# this is not an exhaustive list, you also can use Etc/GMT+n or Etc/GMT-n where n is an offset. %> <div data-tz="Europe/Berlin" class="clock"></div> <div data-tz="Asia/Singapore" class="clock"></div> </div>
额外小优化
- 把你之前重复用的
format('LL')改成了format('LT'),这样一个显示日期一个显示时间,更符合世界时钟的需求。 setTimeout用函数引用代替字符串调用,避免潜在的作用域问题。
内容的提问来源于stack exchange,提问作者Lars Sch
相关产品推荐
相关产品推荐

