鼠标悬停动作只运行一次(how to)

mouseover action run just once (how to)

本文关键字:悬停 一次 how to 运行 鼠标      更新时间:2023-09-26

我想加载数据(通过ajax)在一个工具提示当鼠标在一个特定的区域。问题是,只要我的鼠标在该区域上,就会进行ajax调用。是否有任何方法,我可以使onmouseover (ajax调用)效果只发生一次?下面是代码:

$.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");
            })

.one:

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

.one将在处理程序执行后立即分离处理程序。因此,它不会再执行任何次数。

您可能希望将您的函数与onMouseEnter事件挂钩,而不是onMouseOver事件,以及与隐藏工具提示的onMouseLeave事件挂钩的函数:

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

请注意,这些事件的纯JS版本仅适用于IE, jQuery模拟其他浏览器的行为

使用现代JS!

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

文档,CanIUse

我知道这已经是一个很长的话题了,但是对于那些寻找一个简单的替代方案的人:

设置一个静态变量并检查最后使用的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 
    }
}

我猜你需要使用onmouseenter而不是onmouseover请阅读此处的文档