2011-05-12 73 views
3

我想計算多少時間,我在mouse元素上的鼠標懸停。jquery count懸停事件

爲eample

鏈接

<a class="mylink">Check me Out !</a> 

jQuery的

jQuery('.mylink').hover(function(){ 

//what should i do here to count 
}); 

提前感謝!

+1

這是jQuery的,不是jQuery的 – 2011-05-12 07:21:02

+0

是,;)jQuery是更像...法國! :p – 2011-05-12 07:31:53

+2

在第二次閱讀時,您是否可以澄清一下,如果您想要計算您在某個元素上懸停的次數,或者獲得了在元素上懸停的時間長度? – DarthJDG 2011-05-12 07:33:35

回答

6

如果你想保持獨立的計數器對每個匹配的元素執行以下操作:

jquery('.mylink').mouseover(function(){ 
    var $this = $(this); 
    var count = parseInt($this.data('count'), 10) + 1; 
    $this.data('count', count); 
}); 

然後你就可以得到計數每個元素使用。

編輯:修正了愚蠢的錯誤。

+0

+1:這消除了對全局變量的需求 – Sylvain 2011-05-12 07:29:55

+1

+1非常乾淨的解決方案。也許我很愚蠢,但是你沒有忘記每次都給計數加1嗎? – kapa 2011-05-12 11:53:23

+0

大聲笑,2 upvotes和4小時後,有人注意到它。謝謝。:) – DarthJDG 2011-05-12 16:10:42

4
$(function() 
{ 
    var myCounter = 0; 
    $('.mylink').mouseover(function() 
    { 
     myCounter++; 
    }); 
}); 
0

調用這個函數...

jquery('.mylink').hover(function(){ 

start(true) 
}); 


function start(isStarted, index){ 
if(!index){ 
index = 0; 
} 

if(isStarted) { 
started[index] = true; 
counter[index] =0; 

} 


if(started[index] && true) { 
counter[index] += 1; 
timer = setTimeout("start(false," + index + ")",1000); 
} 

} 
1

如果你想知道你有多少秒,一直徘徊在元素上試試這個:

$('.mylink').hover(
    //mouseover handler 
    function(){ 
     //record the current time 
     $(this).data('start', new Date().getTime()); 
    }, 
    //mouseout handler 
    function(){ 
     //grab the end time 
     var end = new Date().getTime(); 
     //calculate the difference in seconds 
     var hoverTime = (end - $(this).data('start'))/1000; 
     //use the result 
     alert(hoverTime.toFixed(2)); 
    } 
); 
+0

謝謝..這很酷 – Gowri 2011-05-12 07:48:38