在外部JS文件中,JS时钟不起作用

时间:2013-11-15 08:02:26

标签: javascript jsfiddle

我的问题是,当JS时钟直接放在我的HTML文档的头部时似乎工作得很好,但是当我从外部.js文件加载它时无法工作。我的.js文件中的许多其他内容都可以工作,而不是这个!知道问题是什么吗?

    function startTime() {
    var today=new Date(),
        h=today.getHours(),
        m=today.getMinutes(),
        s=today.getSeconds();

    // add a zero in front of numbers<10
    m=checkTime(m);
    s=checkTime(s);
    document.getElementById('bigtime').innerHTML=h+":"+m+":"+s;
}

function checkTime(i) {
    if (i<10) {
        i="0" + i;
    }
    return i;
}

这是fiddle

编辑:我正在我的HTML中加载我的js文件:

<script type="text/javascript" src="js.js"></script>

在我的jquery文件之后。

并在我的js文件中这样:

$(document).ready(function () { 

});

4 个答案:

答案 0 :(得分:1)

我会在jquery库中加载并在JS文件中执行 http://jsfiddle.net/X5njR/

$(document).ready(function (){
startTime();  
});

这使得HTML Cleaner将所有JS保存在一个地方。

答案 1 :(得分:1)

jsFiddle的onLoad选项将您的整个JS包装在//<![CDATA[ window.onload=function(){}//]]>

这意味着直到startTime onload事件处理程序触发后才会定义body函数。

使用No wrap - in <head>选项解决此问题。

答案 2 :(得分:1)

在您的jsFiddle中,您选择了onLoad选项。 如果您从正文中删除内联上传,只需将startTime();放在JavaScript的底部即可。  但那只是在jsFiddle上。在“真实世界”的情况下,您需要在页面加载时使用事件侦听器将脚本放在正文或头部。

jQuery的缩写是$(function() { /* executed after page load */ });

正如您所提到的,您正在使用jQuery,here's a solution with the jQuery onload

function startTime()
{
  /* ... */
}
// after the whole page is loaded, execute the previously declared startTime()
$(function() {
  startTime();
});

答案 3 :(得分:1)

前段时间我用 TypeScript 做了一个时钟。

这里我传递了时钟的功能。

/**
 * @class
 * @name Time
 */
class Time
{
    private millisecond: number;
    private second: number;
    private minute: number;
    private hour: number;
    private day: number;
    private year: number;



    /**
     * @hideconstructor
     * @param {number} millisecond
     * @param {number} second
     * @param {number} minute
     * @param {number} hour
     * @param {number} day
     * @param {number} year
     * @returns {void}
     */
    public constructor(millisecond: number = NaN,
                       second: number = NaN,
                       minute: number = NaN,
                       hour: number = NaN,
                       day: number = NaN,
                       year: number = NaN)
    {
        this.millisecond = millisecond;
        this.second = second;
        this.minute = minute;
        this.hour = hour;
        this.day = day;
        this.year = year;
    }



    //Getters and Setters.
    /**
     * @access public
     * @method
     * @alias Time.getMillisecond
     * @returns {number}
     */
    public getMillisecond(): number
    {
        return this.millisecond;
    }

    /**
     * @access public
     * @method
     * @alias Time.setMillisecond
     * @param {number} millisecond
     * @returns {void}
     */
    public setMillisecond(millisecond: number): void
    {
        this.millisecond = millisecond;
    }

    /**
     * @access public
     * @method
     * @alias Time.getSecond
     * @returns {number}
     */
    public getSecond(): number
    {
        return this.second;
    }

    /**
     * @access public
     * @method
     * @alias Time.setSecond
     * @param {number} second
     * @returns {void}
     */
    public setSecond(second: number): void
    {
        this.second = second;
    }

    /**
     * @access public
     * @method
     * @alias Time.getMinute
     * @returns {number}
     */
    public getMinute(): number
    {
        return this.minute;
    }

    /**
     * @access public
     * @method
     * @alias Time.setMinute
     * @param {number} minute
     * @returns {void}
     */
    public setMinute(minute: number): void
    {
        this.minute = minute;
    }

    /**
     * @access public
     * @method
     * @alias Time.getHour
     * @returns {number}
     */
    public getHour(): number
    {
        return this.hour;
    }

    /**
     * @access public
     * @method
     * @alias Time.setHour
     * @param {number} hour
     * @returns {void}
     */
    public setHour(hour: number): void
    {
        this.hour = hour;
    }

    /**
     * @access public
     * @method
     * @alias Time.getDay
     * @returns {number}
     */
    public getDay(): number
    {
        return this.day;
    }

    /**
     * @access public
     * @method
     * @alias Time.setDay
     * @param {number} day
     * @returns {void}
     */
    public setDay(day: number): void
    {
        this.day = day;
    }

    /**
     * @access public
     * @method
     * @alias Time.getYear
     * @returns {number}
     */
    public getYear(): number
    {
        return this.year;
    }

    /**
     * @access public
     * @method
     * @alias Time.setYear
     * @param {number} year
     * @returns {void}
     */
    public setYear(year: number): void
    {
        this.year = year;
    }



    /**
     * @access public
     * @method
     * @alias Time.today
     * @returns {Date}
     */
    public today(): Date
    {
        return new Date();
    }



    //Time format.
    /**
     * @access public
     * @method
     * @alias Time.year_format
     * @returns {string}
     */
    public year_format(): string
    {
        this.setYear(this.today().getFullYear())

        if (this.getYear().valueOf() >= 0 &&
            this.getYear().valueOf() < 10)
        {
            return `000${this.getYear()}`;
        }
        else
        if (this.getYear().valueOf() >= 10 &&
            this.getYear().valueOf() < 100)
        {
            return `00${this.getYear()}`;
        }
        else
        if (this.getYear().valueOf() >= 100 &&
            this.getYear().valueOf() < 1000)
        {
            return `0${this.getYear()}`;
        }
        else
        {
            return this.getYear().toString();
        }
    }

    /**
     * @access public
     * @method
     * @alias Time.day_format
     * @returns {string}
     */
    public day_format(): string
    {
        this.setDay(this.today().getDate());

        if (this.getDay().valueOf() >= 0 &&
            this.getDay().valueOf() < 10)
        {
            return `0${this.getDay()}`;
        }
        else
        {
            return this.getDay().toString();
        }
    }

    /**
     * @access public
     * @method
     * @alias Time.hour_format
     * @returns {string}
     */
    public hour_format(): string
    {
        this.setHour(this.today().getHours());

        if (this.getHour().valueOf() >= 0 &&
            this.getHour().valueOf() < 10)
        {
            return `0${this.getHour()}`;
        }
        else
        {
            return this.getHour().toString();
        }
    }

    /**
     * @access public
     * @method
     * @alias Time.minutes_format
     * @returns {string}
     */
    public minutes_format(): string
    {
        this.setMinute(this.today().getMinutes());

        if (this.getMinute().valueOf() >= 0 &&
            this.getMinute().valueOf() < 10)
        {
            return `0${this.getMinute()}`;
        }
        else
        {
            return this.getMinute().toString();
        }
    }

    /**
     * @access public
     * @method
     * @alias Time.second_format
     * @returns {string}
     */
    public second_format(): string
    {
        this.setSecond(this.today().getSeconds());

        if (this.getSecond().valueOf() >= 0 &&
            this.getSecond().valueOf() < 10)
        {
            return `0${this.getSecond()}`;
        }
        else
        {
            return this.getSecond().toString();
        }
    }

    /**
     * @access public
     * @method
     * @alias Time.millisecond_format
     * @returns {string}
     */
    public millisecond_format(): string
    {
        this.setMillisecond(this.today().getMilliseconds());

        if (this.getMillisecond().valueOf() >= 0 &&
            this.getMillisecond().valueOf() < 10)
        {
            return `000${this.getMillisecond()}`;
        }
        else
        if (this.getMillisecond().valueOf() >= 10 &&
            this.getMillisecond().valueOf() < 100)
        {
            return `00${this.getMillisecond()}`;
        }
        else
        if (this.getMillisecond().valueOf() >= 100 &&
            this.getMillisecond().valueOf() < 1000)
        {
            return `0${this.getMillisecond()}`;
        }
        else
        {
            return this.getMillisecond().toString();
        }
    }



    //Current.
    /**
     * @access public
     * @method
     * @alias Time.current_month
     * @returns {string}
     */
    public current_month(): string
    {
        //Constants.
        /**
         * @access private
         * @constant
         * @type {Array<string>}
         * @alias months
         */
        const months: Array<string> = [
            `January`,
            `February`,
            `March`,
            `April`,
            `May`,
            `June`,
            `July`,
            `August`,
            `September`,
            `October`,
            `November`,
            `December`
        ];

        /**
         * @access private
         * @constant
         * @type {number}
         * @alias month
         */
        const month: number = this.today().getMonth();

        return months[month];
    }

    /**
     * @access public
     * @method
     * @alias Time.current_day
     * @returns {string}
     */
    public current_day(): string
    {
        //Constants.
        /**
         * @access private
         * @constant
         * @type {Array<string>}
         * @alias week
         */
        const week: Array<string> = [
            `Sunday`,
            `Monday`,
            `Tuesday`,
            `Wednesday`,
            `Thursday`,
            `Friday`,
            `Saturday`
        ];

        /**
         * @access private
         * @constant
         * @type {number}
         * @alias weekday
         */
        const weekday: number = this.today().getDay();

        return week[weekday];
    }
}

/**
 * @class
 * @name Clock
 */
class Clock extends Time
{
    /**
     * @hideconstructor
     * @param {number} millisecond
     * @param {number} second
     * @param {number} minute
     * @param {number} hour
     * @param {number} day
     * @param {number} year
     * @returns {void}
     */
    public constructor(millisecond: number = NaN,
                       second: number = NaN,
                       minute: number = NaN,
                       hour: number = NaN,
                       day: number = NaN,
                       year: number = NaN)
    {
        super
        (
            millisecond,
            second,
            minute,
            hour,
            day,
            year
        );
    }



    /**
     * @access private
     * @method
     * @alias Clock.span_day
     * @param {string} id
     * @returns {HTMLSpanElement}
     */
    private span_day(id: string): HTMLSpanElement
    {
        return (window.document.getElementById(id) as HTMLSpanElement);
    }

    /**
     * @access private
     * @method
     * @alias Clock.span_time
     * @param {string} id
     * @returns {HTMLSpanElement}
     */
    private span_time(id: string): HTMLSpanElement
    {
        return (window.document.getElementById(id) as HTMLSpanElement);
    }



    /**
     * @access private
     * @method
     * @alias Clock.time
     * @returns {string}
     */
    private time(): string
    {
        //Objects.
        /**
         * @access private
         * @constant
         * @type {object}
         * @alias time
         */
        const time: Time = new Time();

        return `${time.hour_format()}:${time.minutes_format()}:${time.second_format()}:${time.millisecond_format()}`;
    }

    /**
     * @access private
     * @method
     * @alias Clock.short_date
     * @returns {string}
     */
    private short_date(): string
    {
        //Objects.
        /**
         * @access private
         * @constant
         * @type {object}
         * @alias time
         */
        const time: Time = new Time();

        return time.today().toLocaleDateString();
    }

    /**
     * @access private
     * @method
     * @alias Clock.long_date
     * @returns {string}
     */
    private long_date(): string
    {
        //Objects.
        /**
         * @access private
         * @constant
         * @type {object}
         * @alias time
         */
        const time: Time = new Time();

        return `${time.current_day()}, ${time.current_month()} ${time.day_format()}, ${time.year_format()}`;
    }



    //Clock.
    /**
     * @access public
     * @method
     * @alias Clock.clock__short
     * @param {string} day_id
     * @param {string} time_id
     * @returns {void}
     */
    public clock__short(day_id: string,
                        time_id: string): void
    {
        window.setInterval(function ()
        {
            /**
             * @access private
             * @constant
             * @type {object}
             * @alias clock
             */
            const clock: Clock = new Clock();

            clock.span_day(day_id).innerHTML = clock.short_date();
        }, 0);

        window.setInterval(function ()
        {
            /**
             * @access private
             * @constant
             * @type {object}
             * @alias clock
             */
            const clock: Clock = new Clock();

            clock.span_time(time_id).innerHTML = clock.time();
        }, 0);
    }

    /**
     * @access public
     * @method
     * @alias Clock.clock__long
     * @param {string} day_id
     * @param {string} time_id
     * @returns {void}
     */
    public clock__long(day_id: string,
                       time_id: string): void
    {
        window.setInterval(function ()
        {
            /**
             * @access private
             * @constant
             * @type {object}
             * @alias clock
             */
            const clock: Clock = new Clock();

            clock.span_day(day_id).innerHTML = clock.long_date();
        }, 0);

        window.setInterval(function ()
        {
            /**
             * @access private
             * @constant
             * @type {object}
             * @alias Clock.clock__long.clock
             */
            const clock: Clock = new Clock();

            clock.span_time(time_id).innerHTML = clock.time();
        }, 0);
    }
}

/**
 * @function
 * @name clock
 * @param {string} day_id This ID refers to the ID of the HTML where you want to put the day.
 * @param {string} time_id This ID refers to the ID of the HTML where you want to put the time.
 * @param {string} type The "type" refers to whether the clock is Long or Short.
 * @returns {void}
 * @summary This function is to insert a clock on the page.
 */
function clock(day_id: string,
               time_id: string,
               type: string): void
{
    try
    {
        //Objects.
        /**
         * @access private
         * @constant
         * @type {object}
         * @alias clock
         */
        const clock: Clock = new Clock();



        if (type === `Long`)
        {
            clock.clock__long(day_id, time_id);
        }
        else
        if (type === `Short`)
        {
            clock.clock__short(day_id, time_id);
        }
    }
    catch (exception)
    {
        window.console.error(`Unexpected error. | Error name: ${(exception as Error).name}; Error message: ${(exception as Error).message}`);
    }
}

至少对我来说,这段代码(已经制作了 JavaScript 并从 Head 中输入)对我有用。我通过从位于 body 标记末尾的 script 标记调用该函数来使其工作。