JavaScript未定义的函数外部JavaScript文件

JavaScript undefined function external JavaScript file

本文关键字:JavaScript 文件 外部 未定义 函数      更新时间:2023-09-26

我加载了一个外部JavaScript文件,并在其中放置了函数,但在运行函数时,它会显示"未定义的函数",但当我将函数放置在索引文件中时,它可以完美地工作。

为了调试这一点,我在输入文档时编写了alert('entered');,并在运行和文档准备就绪时读取内容。两者都被执行。

U得到的错误是:

Uncaught ReferenceError: countdown is not defined
Uncaught ReferenceError: keepalive is not defined

我该怎么解决这个问题?

来源:

   // JavaScript Document
alert('entered js.js');
$(document).ready(function() {
alert('reading content');
    function countdown() {
        var ele = document.getElementsByClassName('countdown');
        for (var i = 0; i < ele.length; ++i) {
            var v = Math.floor(ele[i].getAttribute('ctime')) - 1;
            if (v < 0) {
                v = 0;
            }
            ele[i].setAttribute('ctime', v);
            if (v > 86399) {
                var sl = v;
                d = parseInt(sl / 86400);
                sl = sl % 86400;
                h = parseInt(sl / 3600);
                sl = sl % 3600;
                m = parseInt(sl / 60);
                s = parseInt(sl % 60);
                var str = d + 'd ' + h + 't ' + m + 'm ' + s + 's';
            } else if (v > 3599) {
                var h = Math.floor(v / 60 / 60);
                var m = Math.floor((v - (h * 3600)) / 60);
                var s = v - (m * 60) - (h * 3600);
                var str = h + 't ' + m + 'm ' + s + 's';
            } else if (v > 59) {
                var m = Math.floor(v / 60);
                var s = v - (m * 60);
                var str = m + 'm ' + s + 's';
            } else if (v > 0) {
                var str = v + 's';
            } else {
                var str = ele[i].getAttribute('ctext') || '0s';
            }
            if (v == 0) {
                var act = ele[i].getAttribute('caction');

                if (act != '') {
                    setTimeout(function() {
                        url(act);
                    }, 1000);
                }
            }
            ele[i].innerHTML = str;
        }
        setTimeout('countdown()', 1000);
    }




    $( ".specialpost tr" ).click(function(e) {
        var form = $(this).parents('form').attr('id');
        var submitformId = $(this).data("submitid");
        console.log(form);
        console.log(submitformId);
        $("#submitvalue").val(submitformId);
        $( "#" + form ).submit();
    });


    (function ($) {
        $.fn.countTo = function (options) {
            options = options || {};
            return $(this).each(function () {
                // set options for current element
                var settings = $.extend({}, $.fn.countTo.defaults, {
                    from:            $(this).data('from'),
                    to:              $(this).data('to'),
                    speed:           $(this).data('speed'),
                    refreshInterval: $(this).data('refresh-interval'),
                    decimals:        $(this).data('decimals')
                }, options);
                // how many times to update the value, and how much to increment the value on each update
                var loops = Math.ceil(settings.speed / settings.refreshInterval),
                    increment = (settings.to - settings.from) / loops;
                // references & variables that will change with each update
                var self = this,
                    $self = $(this),
                    loopCount = 0,
                    value = settings.from,
                    data = $self.data('countTo') || {};
                $self.data('countTo', data);
                // if an existing interval can be found, clear it first
                if (data.interval) {
                    clearInterval(data.interval);
                }
                data.interval = setInterval(updateTimer, settings.refreshInterval);
                // initialize the element with the starting value
                render(value);
                function updateTimer() {
                    value += increment;
                    loopCount++;
                    render(value);
                    if (typeof(settings.onUpdate) == 'function') {
                        settings.onUpdate.call(self, value);
                    }
                    if (loopCount >= loops) {
                        // remove the interval
                        $self.removeData('countTo');
                        clearInterval(data.interval);
                        value = settings.to;
                        if (typeof(settings.onComplete) == 'function') {
                            settings.onComplete.call(self, value);
                        }
                    }
                }
                function render(value) {
                    var formattedValue = settings.formatter.call(self, value, settings);
                    $self.text(formattedValue);
                }
            });
        };
        $.fn.countTo.defaults = {
            from: 0,               // the number the element should start at
            to: 0,                 // the number the element should end at
            speed: 1000,           // how long it should take to count between the target numbers
            refreshInterval: 100,  // how often the element should be updated
            decimals: 0,           // the number of decimal places to show
            formatter: formatter,  // handler for formatting the value before rendering
            onUpdate: null,        // callback method for every time the element is updated
            onComplete: null       // callback method for when the element finishes updating
        };
        function formatter(value, settings) {
            return value.toFixed(settings.decimals);
        }
    }(jQuery));



function keepalive() {
    $.ajax({
        url : "http://www.smackface.net/check_user",
        type : "POST",
        dataType : 'json',
        data : {
            method : 'checkAlerts'
        },
        success : function(data, textStatus, XMLHttpRequest) {
            var response = data;

            if (!(response.login)) {
                alert('You are now logging out');
            } else {

            if (response.messages > 0) {
                $('#message_count').show().text(response.messages);
                if ($('#message_count').text() != response.messages) {
                    $("#playsoundappend").html("<audio id='"playsound'"><source src='"http://soundbible.com/grab.php?id=1645&type=mp3'" type='"audio/mpeg'"><source src='"http://soundbible.com/grab.php?id=1645&type=mp3'" type='"audio/mpeg'"></audio>");
                    document.getElementById('playsound').play();
                    $('title').text(response.notifications + " messages");
                }

            }
            else {
                $('#message_count').hide();

            }

            if (response.notifications > 0) {
                $('#notification_count').show().text(response.notifications);
                if ($('#notification_count').text() != response.notifications) {
                    $("#playsoundappend").html("<audio id='"playsound'"><source src='"http://soundbible.com/grab.php?id=1645&type=mp3'" type='"audio/mpeg'"><source src='"http://soundbible.com/grab.php?id=1645&type=mp3'" type='"audio/mpeg'"></audio>");
                    document.getElementById('playsound').play();
                    $('title').text(response.notifications + " notifications");
                }

            }
            else {
                $('#notification_count').hide();

            }
            }

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest.responseText);
        }
    });
    setTimeout('keepalive()', 10000);
}

$("#notificationLink").click(function()
{
    $("#notificationContainer").fadeToggle(300);
    $("#notification_count").fadeOut("slow");

    $.ajax({
        url : "http://www.smackface.net/check_user",
        type : "POST",
        dataType : 'json',
        data : {
            method : 'loadNotifications'
        },
        success : function(data, textStatus, XMLHttpRequest) {
            var tpl = $("#notes").html();
            var notification = Handlebars.compile(tpl);
            $("#notificationsBody").html('');
            $("#notificationsBody").append(notification(data));



        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest.responseText);
        }
    });


    return false;
});
$(document).click(function()
{
    $("#notification_count").hide();
});
$("#notification_count").click(function()
{
    return false;
});

    keepalive();
    countdown();

});

您可以将函数本身传递给setTimeout:

setTimeout(countdown, 1000);
setTimeout(keepAlive, 1000);

按照你写的方式,它必须在$(document).ready(...的范围之外进行"评估"。当您将函数本身作为第一个参数传递时,它就在作用域中。