比较$this选择器和JQuery

Comparing $this selector with JQuery

本文关键字:JQuery 选择器 this 比较      更新时间:2023-09-26

我已经用Flask服务器端编写了一个网站,该网站监视在我运行的其他构建机器上构建的数据。在监控页面上,我有特定机器的当前状态,我每隔几秒钟更新一次。我想能够鼠标在某些机器的名称和工具提示将弹出显示它正在建设的当前数据。我目前拥有将数据服务器端存储在数据库中并轮询数据库的内置功能。但到目前为止,它返回数据的所有状态。我对此很好,但我无法区分它在哪个元素上,所以我无法显示正确的数据。在我的鼠标悬停函数中,我有一个ajax调用,在成功函数中,我已经完成了当前DOM元素的信息。

$('.target').mouseover(function() {
  $.getJSON('/_get_platform', {
    statusID: {{ statusID }}
            }, function(data) {
    var $this=$(this);
    var $tip=$($this.attr('data-tooltip'));
  }); //end getjson
}); //end mouseover

我试图比较$tip与(例如)id #debugTip。因此,如果我知道鼠标位于id为debugTip的元素上,那么我就可以显示与该元素相关的适当数据。

(我已经拿走了所有无关的代码,如工具提示等…为简便起见)

谁能告诉我如何将这与我所知道的东西进行比较?我试过使用$tip == '#debugTip'和$tip.is('#debugTip'),但要么不起作用,要么我没有正确使用它。有人知道我错在哪里吗?

提前感谢!!

您只能在执行ajax请求之前访问this。因此,您必须在进入ajax回调之前存储提示。

$('.target').on( 'mouseover', function() {
  // get the tip, while we still have 'this' object (before the ajax)
  var $tip = $($(this).data('tooltip'));
  $.getJSON('/_get_platform', {
    statusID: {{ statusID }}
  }, function(data) {
    // check if it's a debug tooltip
    if ( $tip.is('#debugTip') ) {
      console.log("it's the debug tip");
    } else {
      console.log("normal tooltip");
    }
  }); //end getjson  
}); //end mouseover

如果你想检查$('.target')元素是否有"#debugTip" ID,那么你可以这样做:

if($tip.is("#debugTip")){
    console.log('Debug data here');
}

如果你需要引用鼠标悬停的元素,你需要将其保存在一个变量中,然后你可以在$. getjson的回调中引用它。

$('.target').mouseover(function() {
                        var mouseOveredElement = $(this);
                        $.getJSON('/_get_platform', {
                              statusID: {{ statusID }}
                        }, function(data) {
                              var tip=$(mouseOveredElement).attr('data-tooltip');
                        }); //end getjson
                     });    //end mouseover