我试图传递“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);
}
);
});
答案 0 :(得分:2)
调用displayDate
函数的时间,进入另一个范围,this
是您的窗口对象(不再是div元素)。要解决此问题,您可以这样做:
$(".test").hover( function() {
var self = this;
myVar = setInterval(function() {
displayDate(self);
},1000);
}, function() {
clearInterval(myVar);
});
答案 1 :(得分:0)
而不是setInterval(“displayDate(this)”,100);
$(".test").hover( function() {
var that = $(this);
setInterval(function () {
displayDate(that);
},100);