日期插件 bootstrap-datetimepicker 在火狐下出現一條報錯信息:TypeError: (intermediate value).toString(…).split(…)[1] is undefined
這條錯誤必然出現,難道沒有在 Firefox 下進行測試。
在 Firefox 下查看項目 demo (http://www.malot.fr/bootstrap-datetimepicker/demo.php)可以正常運行,但這個 demo.php 使用的是 2013-3-2 的 datetimepicker,github 項目(https://github.com/smalot/bootstrap-datetimepicker/releases)已經發布到 2017-3-3,這個最新的版本(以及最近的一些版本)在 Firefox 下測試不完善,計算 defaultTimeZone 時雖然沒有出錯,但給出的結果也不正確。
源代碼如下,運行環境 Firefox 51.0.1(32位)
this.defaultTimeZone = (new Date).toString().split('(')[1].slice(0, -1);this.timezone = options.timezone || this.defaultTimeZone;// 2.4.4 改進版本this.timezone = options.timezone || timeZoneAbbreviation();function timeZoneAbbreviation() { var abbreviation, date, formattedStr, i, len, matchedStrings, ref, str; date = (new Date()).toString(); formattedStr = ((ref = date.split('(')[1]) != null ? ref.slice(0, -1) : 0) || date.split(' '); if (formattedStr instanceof Array) { matchedStrings = []; for (var i = 0, len = formattedStr.length; i < len; i++) { str = formattedStr[i]; if ((abbreviation = (ref = str.match(//b[A-Z]+/b/)) !== null) ? ref[0] : 0) { matchedStrings.push(abbreviation); } } formattedStr = matchedStrings.pop(); } return formattedStr;}出錯原因是 Firefox 下 Date.prototype.toString 返回結果不包含 TimeZone 的文字描述。
2.4.4 改進版本使用的 timeZoneAbbreviation 函數在 Firefox 下返回 true
對 timeZoneAbbreviation 使用的三元表達式依次簡化
((abbreviation = (ref = str.match(//b[A-Z]+/b/)) !== null) ? ref[0] : 0)(abbreviation = (ref = str.match(//b[A-Z]+/b/)) !== null)(abbreviation = (xxx) !== null)(abbreviation = xxx !== null)abbreviation 必然是布爾值,如果將 matchedStrings.push(abbreviation) 換成 matchedStrings.push(str) 更接近預期值。
推薦使用文末的方案。

解決方案
將 date toString 最后一個空格之后的字符串作為 TimeZone。
// this.defaultTimeZone = (new Date).toString().split('(')[1].slice(0, -1);this.defaultTimeZone = (new Date + '').split(' ').slice(-1)[0].replace(//(|/)/g, '');this.timezone = options.timezone || this.defaultTimeZone;以上所述是小編給大家介紹的 bootstrap datetimepicker 日期插件在火狐下出現一條報錯信息的原因分析及解決辦法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答