来自另一个.js文件的功能不起作用

时间:2015-02-27 02:58:08

标签: javascript


我想在我的页面上显示日期。当我在<script>标记中创建一些函数时,代码工作正常。我想将这两个函数放在另一个.js文件中,这样代码看起来就不那么混乱了。但是,当我这样做时,功能似乎不起作用。我的index.html和custom.js位于同一个文件夹中。有什么我做错了吗?谢谢!

我的简化index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="custom.js"></script>
    </head>
    <body>
        <script>
        document.write('<h1>' + returnWeek() + ', ' + returnMonth(false) + ' ' + new Date().getDate() + ', ' + new Date().getFullYear() + '</h1> <small>' + returnMonth(true) + '.' + new Date().getDate() + '.' + new Date().getFullYear() + '</small>');
        </script>
    </body>
</html>

我的custom.js:

function returnWeek() {
    switch (new Date().getDay()) {
        case 0:
            return 'Sunday';
        case 1:
            return 'Monday';
        case 2:
            return 'Tuesday';
        case 3:
            return 'Wednesday';
        case 4:
            return 'Thursday';
        case 5:
            return 'Friday';
        case 6:
            return 'Saturday';
    }
}
function returnMonth(num) {
    if (num == true) {
        return new Date().getMonth() + 1;
    } else {
        switch (new Date().getMonth()) {
            case 0:
                return 'January';
            case 1:
                return 'February';
            case 2:
                return 'March';
            case 3:
                return 'April';
            case 4:
                return 'May';
            case 5:
                return 'June';
            case 6:
                return 'July';
            case 7:
                return 'August';
            case 8:
                return 'September';
            case 9:
                return 'October';
            case 10:
                return 'November';
            case 11:
                return 'December';
        }
    }
}

修改:点击here查看完整代码!我最初将custom.js的内容放在document.write()的正上方。

2 个答案:

答案 0 :(得分:0)

我已经通过调用外部.js文件在Opera,Firefox 35.0.1,Chrome和IE 11上测试了您的代码;它是完美的,因为它根据我的机器日期返回日期。所以请检查你的浏览器,因为Igor建议清理缓存。

答案 1 :(得分:0)

我怀疑发生的事情是你的HTML文件加载速度比JS文件快。通过立即执行代码(即使它位于HTML文件的底部),它可能会挂起,因为这些方法在技术上尚未加载。在页面加载后尝试执行代码。

function initPage () {
    document.write('<h1>' + returnWeek() + ', ' + returnMonth(false) + ' ' + new Date().getDate() + ', ' + new Date().getFullYear() + '</h1> <small>' + returnMonth(true) + '.' + new Date().getDate() + '.' + new Date().getFullYear() + '</small>');
}

if (window.addEventListener) {
    window.addEventListener("load", initPage, false);
} else {
    window.onload = initPage;
}
相关问题