我在ie8上遇到以下javascript错误:
<script type="text/javascript">
//when html doc is all ready
$(document).ready(function () {
var socket = io.connect();
var room = 'public';
socket.emit('join', room);
socket.on('message', function (data) {
var output = '';
output += '<div class="trace-content">';
output += ' <div class="mname">' + data.name + '</div>';
output += ' <div class="mdate">' + data.date + '</div>';
output += ' <p class="mtext">' + data.message + '</p>';
output += '</div>';
$(output).prependTo('#traces');
});
$('button').click(function () {
var date = new Date().toISOString();
socket.emit('message', {
name: $('#name').val(),
message: $('#message').val(),
date: date.slice(2,10) + ' ' + date.slice(11, 19)
});
});
});
</script>
问题似乎在于:var date = new Date()。toISOString(); 我无法确定问题的确切位置。 其他一切似乎都很好;只需按下该按钮,然后执行代码。有什么想法吗?
答案 0 :(得分:24)
IE8不支持.toISOString()
。您可以将此代码用作垫片(来自Mozilla):
if ( !Date.prototype.toISOString ) {
(function() {
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear()
+ '-' + pad( this.getUTCMonth() + 1 )
+ '-' + pad( this.getUTCDate() )
+ 'T' + pad( this.getUTCHours() )
+ ':' + pad( this.getUTCMinutes() )
+ ':' + pad( this.getUTCSeconds() )
+ '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+ 'Z';
};
}() );
}
答案 1 :(得分:3)
当然,您收到错误http://kangax.github.com/es5-compat-table。在Google中查找 date.prototype.toISOString()polyfill 。找到了这个https://gist.github.com/1044533
从要点:
// thanks to @fgnass and @subzey for their awesome golf skills
// annotation by @fgnass
function(a){
a=this;
return (
1e3 // Insert a leading zero as padding for months < 10
-~a.getUTCMonth() // Months start at 0, so increment it by one
*10 // Insert a trailing zero as padding for days < 10
+a.toUTCString() // Can be "1 Jan 1970 00:00:00 GMT" or "Thu, 01 Jan 1970 00:00:00 GMT"
+1e3+a/1 // Append the millis, add 1000 to handle timestamps <= 999
// The resulting String for new Date(0) will be:
// "-1010 Thu, 01 Jan 1970 00:00:00 GMT1000" or
// "-10101 Jan 1970 00:00:00 GMT1000" (IE)
).replace(
// The two digits after the leading '-1' contain the month
// The next two digits (at whatever location) contain the day
// The last three chars are the milliseconds
/1(..).*?(\d\d)\D+(\d+).(\S+).*(...)/,
'$3-$1-$2T$4.$5Z')
}
注意:这可能不是最易读的代码或polyfill的最佳示例,但它似乎根据要点中的注释工作,因此它是一个快速复制/粘贴解决方案。
答案 2 :(得分:0)
为什么不使用toJSON method? IE8支持它。