2011-07-20 59 views
2

我想在鼠標懸停在特定區域時在工具提示中加載數據(通過ajax)。問題是,只要我的鼠標在該區域上就可以進行ajax調用。有什麼辦法,我可以讓onmouseover(ajax call)效果只發生一次?下面是代碼:鼠標懸停操作只運行一次(如何)

$.post('calendar/event-details', {'eventId' :event.id}, 
      function (data){ 
       this.top = (ui.clientY + 15); this.left = (ui.clientX - 230); 
       $('body').append('<div id="vtip">' + data + '</div>'); 
       $('div#vtip').css("top", this.top+"px").css("left", this.left+"px").fadeIn("slow"); 
       $('div#vtip').css("position","absolute"); 
       $('div#vtip').css("z-index", "+99"); 
      }) 
+0

哪裏是你的HTML,並在那裏爲你的代碼結合的鼠標懸停事件? – Shef

回答

12

隨着.one

$('element').one('mouseover', function() { /* ajax */ }); 

.one會盡快,因爲它是執行分離處理程序。因此,它不會再執行任何操作。

+0

+1這太棒了! – Nate

6

您可能要掛鉤的函數來onMouseEnter事件而不是onMouseOver事件,與掛在onMouseLeave事件函數隱藏工具提示一起:

$('element').mouseenter(function() { 
    /* Make request, show tooltip */ 
}); 
$('element').mouseleave(function() { 
    /* Hide tooltip */ 
}); 

注意的純JS版本這些事件只有IE瀏覽器,jQuery的模擬其他瀏覽器

+0

幫了我很多!謝謝。 – Rikco

0

我知道這是一個漫長的時間,因爲這一直是一個課題,但爲尋找一個簡單的替代行爲:

設置一個靜態變量並檢查使用的最後一個ID。 如果最後一個id是當前的id,什麼都不做;下面的快速示例

var LastId = null; 

function Hover(Id){ 
    if(Id!= LastId){ 
     LastId = Id; 
     $(Id).hide('fast'); 
    }else{ 
     //Do nothing; this will keep the function from recalling 
    } 
} 
0

使用現代JS!

node.addEventListener("mouseover", function() { 
    // Load data here 
}, {once : true}); 

DocumentationCanIUse