繁体   English   中英

jquery悬停不开火

[英]jquery hover not firing

我正在尝试添加套接字消息的新客户端。 我想在悬停时扩展它们。

在这里阅读一些答案,但没有任何作用。 我不知道为什么

我试过了

socket.on('newStudentJoined', function studentJoined(msg) {
    console.log(msg.student + ' joined the room');
    $(document.createElement('div'))
        .attr('class', 'studentIcon closed col-md-2 ' + msg.student)
        .text(msg.student + ' 4r3 g345t g354 g54 ght65 g45t 3f4 f4 f4 534 g534')
        .on('hover', function() {
            console.log('hovering');
            $(this).toggleClass('closed').toggleClass('open');
        })
        .appendTo('#joinedClients');
});

$('.studentIcon').on('hover', function() {
    console.log('hovering');
    $(this).toggleClass('closed').toggleClass('open');
});

但即使是“悬停”的控制台日志也没有出来。 选择器是正确的,如果我记录它,它会突出显示确切的元素。 确保;确定:

<div id="joinedClients" class="row">
    <div class="studentIcon closed col-md-2 test">test 4r3 g345t g354 g54 ght65 g45t 3f4 f4 f4 534 g534</div>
</div>

这有什么不对?

请改用mouseover

$(document).on('mouseover', '.studentIcon',function() {
    console.log('hovering');
    $(this).toggleClass('closed').toggleClass('open');
});

或使用

$(document).on("mouseenter mouseleave", ".studentIcon", function (e) {
  if (e.type == "mouseenter") {
    // check if it is mouseenter, do something
  } else {
    // if not, mouseleave, do something
  }
});

.hover()方法结合处理程序两者mouseentermouseleave事件。 您可以使用它在鼠标位于元素中时简单地将行为应用于元素。

这是因为您在有问题的元素存在之前绑定事件(因为您使用javascript创建元素)。

您需要创建事件绑定事件,或者按如下方式定位侦听器

$('#joinedClients').on('hover', '.studentIcon', function() {
    console.log('hovering');
});

由于您使用的是JQuery,请使用.hover():

$('.studentIcon').hover(//stuff);

'悬停'不是真实的事件。 jQuery提供了一个辅助函数 .hover(enterfunc, leavefunc) ,相当于:

$('#mydiv').on({'mouseenter': enterfunc, 'mouseleave': leavefunc})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM