这个非常基本的脚本会在页面上创建3个变量,今天会以首选格式显示,日期从今天起+90天,从今天起+120天。
它在Firefox和IE上运行良好,但在Chrome中,这些变量显示为“未定义”,控制台输出: “未捕获的TypeError:对象false没有方法'setDate'”
这是我的JavaScript
var today = new Date();
var rg = (today.getMonth()+1) + "/" + today.getDate() + "/" + today.getFullYear();
var closed = new Date();
closed.setDate(today.getDate()+90);
var cl = (closed.getMonth()+1) + "/" + closed.getDate() + "/" + closed.getFullYear();
var expire = new Date();
expire.setDate(today.getDate()+120);
var ex = (expire.getMonth()+1) + "/" + expire.getDate() + "/" + expire.getFullYear();
答案 0 :(得分:1)
closed
是任何window
个对象的保留名称。 (请参阅here)由于您在全局空间中运行此变量,因此所有变量都存储在window
下方,因此您与浏览器认为window.closed
应该出现的内容发生冲突。< / p>
只需将var closed = new Date();
更改为新名称,或者@KingKongFrog建议通过闭包将其放入新范围。
答案 1 :(得分:1)
将其放在匿名函数中并尝试
(function() {
var today = new Date();
var rg = (today.getMonth()+1) + "/" + today.getDate() + "/" + today.getFullYear();
var closed = new Date();
closed.setDate(today.getDate()+90);
var cl = (closed.getMonth()+1) + "/" + closed.getDate() + "/" + closed.getFullYear();
var expire = new Date();
expire.setDate(today.getDate()+120);
var ex = (expire.getMonth()+1) + "/" + expire.getDate() + "/" + expire.getFullYear();
})();