一个mouseleave事件将$(this)记录为元素;另一个将其作为委托对象进行日志记录

One mouseleave event logs $(this) as element; another logs it as delegated object

本文关键字:记录 对象 日志 另一个 元素 事件 mouseleave this 一个      更新时间:2023-09-26

我已将mouseleave事件附加到两个HTML元素。我很困惑为什么在一个将$(this)打印到控制台的过程中显示事件所附加的div元素,而另一个打印出整个window

$(function () {
  $(document).on({
    mouseenter: function (evt) {
        $(evt.target).data('hovering', true);
    },
    mouseleave: function (evt) {
        $(evt.target).data('hovering', false);
    }
  }, "*");
  $.expr[":"].hovering = function (elem) {
    return $(elem).data('hovering') ? true : false;
  };
  $(document).on({
      mouseenter: function () {
          var $menu = $(".menu[data-a='" + $(this).attr("data-a") + "']");
          //console.log($menu)
          $menu.addClass("menu_vis");
          $(".menu").hide();
          $menu.show();
      },
      mouseleave: function () {
          console.log($(this)) //the div
          var s = setTimeout(function () {
              var $menu = $(".menu[data-a='" + $(this).attr("data-a") + "']");
              var over_menu = $menu.is(":hovering");
              if (!over_menu) {
                  $menu.hide();
              }
          }, 100);
      }
    }, ".activate");
    $(document).on({
        mouseleave: function () {
          var s = setTimeout(function(){
          var $activate = $(".activate[data-a='" + $(this).attr("data-a") + "']");
          var over_activate = $activate.is(":hovering");
          console.log($(this)); //the window ??
             if (!over_activate){
               $(this).hide();
             }
          }, 100)
        }
    }, ".menu");
});

在嵌套函数中,this关键字指的是window。(您使用的是setTimeout,即嵌套在mouseleave中)

要解决:在使用嵌套函数之前使用变量

var that = $(this);
//now when you use function, use like this:
setTimeout(function(){
console.log(that);//logs the Div
},100)

或者使用绑定方法:

setTimeout(function(){
console.log($(this));//logs the Div
}.bind(this),100)