简体   繁体   中英

JavaScript Error: Object expected

I have an HTML page featuring a div with right-to-left scrolling text; the following JavaScript is located between the HEAD tags of the document.

function scroll(oid, iid) {
            this.oCont = document.getElementById(oid);
            this.ele = document.getElementById(iid);
            this.width = this.ele.clientWidth;
            this.n = this.oCont.clientWidth;
            this.move = function() {
                this.ele.style.left=this.n + "px"
                this.n--
                if(this.n<(-this.width)){this.n=this.oCont.clientWidth}
            }
        }
        var vScroll
        function setup() {
            vScroll = new scroll("oScroll", "scroll");
            setInterval("vScroll.move()", 20);
            }           
        onload = function(){
            setup()
        }

        $("scroll").hover(function() {
            $("scroll").stop(true, false)
        }, function(){
            scroll();
        });
        scroll();

The scrolling text works fine; however I wanted the scrolling to stop on mouse hover. Although the text does stop scrolling when the mouse cursor passes over the div, I get a javascript error "Object expected". I'm new to javascript and have no idea where I'm going wrong.

Any help would be greatly appreciated.

Your problem is with your setInterval . You are passing it a string! This makes it use eval ! That means the code is ran in global scope, so vScroll does not exist.

Instead, pass a function to setInterval :

setInterval(function(){
    vScroll.move();
}, 20);

The function passed to setInterval is called with the "context" ( this value) set to null , so you cannot pass vScroll.move directly to setTimeout . You can, however. do:

setInterval(vScroll.move.bind(vScroll), 20);

but this doesn't work in all browsers.

PS Passing a string to setInterval is bad practice, you should always be passing a function.

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