简体   繁体   中英

Uncaught ReferenceError, my function is not defned

I'm creating a dyanamic scrolling div and it works fine on Jsfiddle as seen here --> http://jsfiddle.net/9zXL5/19/embedded/result/ yet on the browser I get:

Uncaught TypeError: Cannot set property 'onscroll' of null

So then I added $(document).ready(function (){ to my code and got

Uncaught ReferenceError: yHandler is not defined

I'm not understanding why I'm getting these errors yet its flowing smoothly on jsfiddle. I'd really appreciate it if someone could tell me what I'm not understanding or missing. Code in question is below

var movelist = document.getElementById('movelist');
    $(document).ready(function (){
    function  yHandler (){
        var contentHeight = movelist.scrollHeight;
        var yOffset = movelist.clientHeight;
        var y = yOffset + movelist.scrollTop;
        if(y >= contentHeight){
            movelist.innerHTML += '<div class ="newData">hey look at me</div>';
        }
    }
});
movelist.onscroll = yHandler;

Put

var movelist = document.getElementById('movelist');

and

movelist.onscroll = yHandler;

inside your document.ready call.

Or, get rid of the document.ready call (you don't seem to have any jQuery in there anyway) and put your code in a script block at the end of your document before the closing body tag.

jsFiddle example

您需要在标签$(document).ready(function (){...});之外定义函数$(document).ready(function (){...});

It's working in your Fiddle because everything is in the same scope. You are declaring movelist outside your $(document).ready . Move both the var movielist = ... and movielist.onscroll = yHandler; inside your $(document).ready .

You can also move your yHandler function outside your $(document).ready .

You should move all your code to within the onload handler

$(document).ready(function (){
    var movelist = document.getElementById('movelist');
    function  yHandler (){  
        var contentHeight = movelist.scrollHeight;
        var yOffset = movelist.clientHeight;
        var y = yOffset + movelist.scrollTop;

        if(y >= contentHeight){
            movelist.innerHTML += '<div class ="newData">hey look at me</div>';
        }          
    }
    movelist.onscroll = yhandler
});

Now your yhandler is within the same scope as the place that is using it. In your example, it was defined an as inner function, and you were trying to access it from outside the function. When you define inner functions, they are like local variables, they can only be access by the function itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM