最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery: Uncaught ReferenceError: function is not defined - Stack Overflow

programmeradmin1浏览0评论

I have this code:

<script>
    $(function () {
        function back_to_top(){
            $('body,html').animate({scrollTop: 0}, 100);
        }
    });
</script>

<div class="toTop" onClick="back_to_top();">To up!</div>

When I click to this button, chrome show me this error: Uncaught ReferenceError: back_to_top is not defined. Where is my mistake?

I have this code:

<script>
    $(function () {
        function back_to_top(){
            $('body,html').animate({scrollTop: 0}, 100);
        }
    });
</script>

<div class="toTop" onClick="back_to_top();">To up!</div>

When I click to this button, chrome show me this error: Uncaught ReferenceError: back_to_top is not defined. Where is my mistake?

Share Improve this question asked Feb 23, 2015 at 13:58 Dmitry GDmitry G 931 silver badge8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

It's because the jQuery DOM ready function creates a new scope, enclosing your function, which means it's not accessible from the global scope. Inline events must be in the global scope.

function back_to_top(){
    $('body,html').animate({scrollTop: 0}, 100);
}
$(function () {

});

Or drop the inline handler and use unobtrusive JavaScript.

$(function () {
    function back_to_top(){
        $('body,html').animate({scrollTop: 0}, 100);
    }

    $('.toTop').click(function(){
        back_to_top();
    });
});

HTML with no inline handler:

<div class="toTop">To up!</div>

You have to put back_to_top outside the jquery document ready function

JavaScript has function scope. That means that variables (including function declarations) defined within a function, will only be available in that function. i.e. in this case back_to_top is only accessible within the $(function(){...}).

...onClick="back_to_top();" is looking at the global scope and back_to_top is not available. You can expose it though if you do something like this:

$(function () {
        window.back_to_top = function {
            $('body,html').animate({scrollTop: 0}, 100);
        }
    });

I don't think this is ideal but it will work in your case. A better way is to attach a listener. Have a look at jQuery click method.

Hope it helps.

发布评论

评论列表(0)

  1. 暂无评论