简体   繁体   English

JavaScript错误:预期对象

[英]JavaScript Error: Object expected

I have an HTML page featuring a div with right-to-left scrolling text; 我有一个HTML页面,其中包含一个具有从右到左滚动文本的div的页面; the following JavaScript is located between the HEAD tags of the document. 以下JavaScript位于文档的HEAD标签之间。

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". 尽管当鼠标指针移到div上时文本不会停止滚动,但是我收到了一个JavaScript错误“ Object Object Expected”。 I'm new to javascript and have no idea where I'm going wrong. 我是javascript的新手,也不知道我要怎么做。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Your problem is with your setInterval . 您的问题出在setInterval You are passing it a string! 您正在传递一个字符串! This makes it use eval ! 这使它使用eval That means the code is ran in global scope, so vScroll does not exist. 这意味着代码在全局范围内运行,因此vScroll不存在。

Instead, pass a function to setInterval : 而是将一个函数传递给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 . 调用传递给setInterval的函数时vScroll.move “上下文”( this值)设置为null ,因此无法将vScroll.move直接传递给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. PS将字符串传递给setInterval是不好的做法,您应该始终传递一个函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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