0

我正在尝试从以下位置传递“这个”:

myVar = setInterval("displayDate(this )",1000);

并且当我逐步通过它时正在通过“div.test”,但是在接收它时:

function displayDate(obj){
}

它说它是“窗口”???下面是我正在构建的 JavaScript。我正在尝试为触发事件的类建立基础,最终我将通过 Sprite 解析以可变速率(现在设置为 100)更改 elements.src=".jpg"。但我目前坚持这一点,我不想在 .html 代码中插入 onmousemove 属性等以保持干净。. . 请记住,这只是我写 .html/.css/.js 的第三天,因此感谢您的帮助!

// This helps create a static variable that isn't polluting the global namespace
var incr = (function () {
    var i = 0;
    return function(){ return i++; };
})();

// This perform all of the functions that we would like with some error handling
function displayDate(obj){

    var counter = incr();

    try{
        obj.innerHTML=counter;
    }catch(err){
        var txt="There was an error on this page.\n\n";
        txt+="Error description: " + err.message + "\n\n";
        txt+="Click OK to continue.\n\n";
        alert(txt);
    }
}

// This is our trigger that sets an interval for our main Java function
$(function(){
    var myVar;
    $(".test").hover( function() {
        // The mouse has entered the element, can reference the element via 'this'
        myVar = setInterval("displayDate(this )",100);
    },function () {
        // The mouse has left the element, can reference the element via 'this'
        clearInterval(myVar);
    }
    );
});
4

2 回答 2

2

调用该displayDate函数的时间,您进入另一个范围并且this是您的窗口对象(不再是 div 元素)。要解决,您可以这样做:

$(".test").hover( function() {
    var self = this;

    myVar = setInterval(function() {
        displayDate(self);
    },1000);
}, function() {
    clearInterval(myVar);
});
于 2013-10-10T21:38:10.267 回答
0

而不是 setInterval("displayDate(this)",100);

$(".test").hover( function() {
var that = $(this);
setInterval(function () {
displayDate(that);

},100);
于 2013-10-10T21:38:58.247 回答