javascript 鼠标悬停动作只运行一次(如何)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6759235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:45:33  来源:igfitidea点击:

mouseover action run just once (how to)

javascriptjqueryajax

提问by sica07

I would like to load data(via ajax) in a tooltip when the mouse is over a specific area. The problem is that the ajax call is made as long as my mouse is on that area. Is there any way, that I could make onmouseover (ajax call) efect happen just once? Here is the code:

当鼠标悬停在特定区域上时,我想在工具提示中加载数据(通过 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");
            })

回答by pimvdb

With .one:

.one

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

.onewill detach the handler as soon as it is executed. As a result, it won't execute any more times.

.one将在执行后立即分离处理程序。结果,它将不再执行。

回答by You

You may want to hook your function to the onMouseEnterevent instead of the onMouseOverevent, along with a function hooked to the onMouseLeaveevent that hides the tooltip:

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

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

Note that the pure JS versions of these events are IE only, jQuery simulates the behaviour for other browsers

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

回答by Gibolt

Use modern JS!

使用现代JS!

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

Documentation, CanIUse

文档, CanIUse

回答by MattOlivos

I know it's been a long time since this has been a topic but for anyone looking for an easy alternative:

我知道这已经是一个话题很久了,但对于任何寻找简单替代方案的人来说:

Set a static variable and check the last id used. If the last id is the current id, do nothing; quick example below

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