使用jQuery

时间:2016-11-16 04:23:52

标签: jquery html

我正在尝试向管理员提供他们正在悬停的元素的鼠标悬停,以便为他们提供编辑内容的线索,如果有的话。这是我的代码:

$(document).tooltip();
$(document).on('mouseover','*',function(){
  $(this).attr('title',$(this).prop('id'));
  console.log($(this));
}).on('mouseout',function(){
  $(this).attr('title','');
});

这适用于具有id的元素。我需要得到的是 html 元素和鼠标悬停上的ID(如果有)的组合。

3 个答案:

答案 0 :(得分:1)

如果我理解正确,当您将鼠标悬停在元素上时,您需要元素的ID以及元素类型(标记名称)。如果是这种情况,那么您可以使用以下内容:

 $(document).on('mouseover','*',function(){
      var id = this.id;
      var elementType = $(this).prop('nodeName'); // will give you element tag name
      // do something with id and elementType
    }).on('mouseout',function(){
      $(this).attr('title','');
    });

答案 1 :(得分:0)

您应该可以使用this.id代替$(this)...缩短代码 同时检查您的控制台并从那里选择您需要的,并使用||操作员选择最适合您的那个。

$(document).on('mouseover','*',function(){
  $(this).attr('title',(this.id || some_other_things || yet_another_one));
  console.log($(this));
  console.log(this);
}).on('mouseout',function(){
  $(this).attr('title','');
});

答案 2 :(得分:0)

如果未定义id,则获取dom元素的tagName属性。

$(this).attr('title', this.id || this.tagName);