【问题标题】:Return immediately and not execute chained mouseout event if mousedown was triggered inside mouseover event如果 mousedown 在 mouseover 事件中触发,则立即返回并且不执行链接的 mouseout 事件
【发布时间】:2012-05-02 20:14:34
【问题描述】:

不知道该怎么做,但基本上我写了一个工具提示插件,它删除了mouseoutmousedown 上的工具提示。

如果触发了mousedown 事件,它将删除$that.parent(),这很好,这会删除工具提示,但是如果用户还触发了 mouseout 事件(他们会因为 mouseover 和 @ 987654326@ 事件当前被链接),然后它将删除另一个我不想要的 DOM 元素。所以基本上我想知道这是否可能:

$that.on('mouseover', function() {

    // If this event is triggered within the mouseover event, don't run the chained mouseout event
    $that.on('mousedown', function() {
        $that.parent().next().fadeOut(100).remove();
        return false;
    });
}).mouseout(function() {
  // If they clicked above, don't run this
    $that.parent().next().fadeOut(100).remove();
});​

据我所知,如果不使用全局变量,很难访问 clicked 事件中的 clicked 布尔集,例如:

$that.on('mouseover', function() {
    clicked = false;
    // If this event is triggered within the mouseover event, don't run the chained mouseout event
    $that.on('mousedown', function() {
        clicked = true;
        $that.parent().next().fadeOut(100).remove();
        return false;
    });
}).mouseout(function() {
    // If they clicked above, don't run this
    if (clicked) {
        $that.parent().next().fadeOut(100).remove();
    }
});​

关于如何优雅地构建它有什么想法吗?

编辑:$that.parent().next() 中的元素只是 <div class="js-tooltip"><span>Tooltip text</span></div>

但这应该无关紧要,因为我只想知道如果在不使用全局变量的情况下触发了 mousedown,是否可以从该 mouseover 函数返回。

【问题讨论】:

  • 您应该更好地解释一下确切指向哪些元素:$that.parent().next().fadeOut(100).remove(); 我的意思是:$that 是什么,什么元素是:parent,谁是:.next()?你说 $that.parent() 删除了工具提示,但 .next() 的目的是什么???
  • @RokoC.Buljan $that.parent().next() 是在被点击的当前元素之后被克隆并插入到 DOM 中的工具提示。 $that 在这种情况下指的是一个名为 Cancel 的输入按钮,它添加了带有一些文本的工具提示:“Discard Changes”

标签: javascript jquery mouseover jquery-events mousedown


【解决方案1】:

您不需要mouseover

$that.on('mouseleave mouseup', function(e) {
     if( e.type === 'mouseleave'){
         // do the mouseleave stuff
     }else{
         // do the mouseup stuff
     }
});​

如你所说,如果元素是动态创建的,你应该使用:

$(document).on('mouseleave mouseup', $that, function(e) {

【讨论】:

  • 虽然这并没有解决我的问题,但它通过 e.mouseleave 检测向我介绍了一种新的事件方式,这是我以前不知道可以做到的。非常感谢!!!
【解决方案2】:

您是否考虑过像这样简单地使用类过滤器?

$that.parent().next('.js-tooltip').fadeOut(100).remove();

如果下一个不是工具提示,这根本不会做任何事情,据我所知,这应该可以解决问题。

使用您提出的方法,$that.clicked = false 会更清晰。

或者怎么样(如果你想保持鼠标悬停 - 这只是为了演示原理;我不确定它是否会这样工作):

$that.on('mouseover', function() {

    // If this event is triggered within the mouseover event, don't run the chained mouseout event
    $that.on('mousedown mouseout', function() {
        $that.parent().next().fadeOut(100).remove();
        $that.off('mousedown mouseout'); //prevent that happening again
        return false;
    });
});

【讨论】:

  • 老兄!我不知道为什么我之前没有针对.js-tooltip。这更有意义,现在我的附加元素没有被删除。谢谢!!!
猜你喜欢
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 2015-02-25
  • 2011-04-13
相关资源
最近更新 更多