JavaScript 传递元素但接收窗口

JavaScript Passing Element but Receiving Window?

本文关键字:窗口 元素 JavaScript      更新时间:2023-09-26

我正在尝试从以下位置传递"this":

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);
    }
    );
});
调用

displayDate函数的时间,你进入另一个作用域,this是你的窗口对象(不再是div元素(。要解决此问题,您可以执行以下操作:

$(".test").hover( function() {
    var self = this;
    myVar = setInterval(function() {
        displayDate(self);
    },1000);
}, function() {
    clearInterval(myVar);
});

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

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