使用Jquery选择类元素

Selecting class element with Jquery

本文关键字:元素 选择 Jquery 使用      更新时间:2023-09-26

我的页面上有一些元素。以下是其中的一些:

<div class="tile 11"></div>
<div class="tile 35"></div>
<div class="tile 89"></div>

我想要一个CLASS的元素在我悬停它的时候进入变量

我试着

$(".tile").mouseenter(function(){            //on mouse over
  $(this).css("background-color", "red");    //check if selected
  myVariable = $(this).css;                  //then place css into variable
    }).mouseleave(function() {               //..and when I leave it
      $( this ).removeAttr( "style" );       //remove color
});

但是没有成功。

例如,当我将第一个tile悬停时,"myVariable"应该是"tile 11",但它不是。为什么?

这很简单。您需要使用$(this).attr("class"),如下所示。

$(".tile").mouseenter(function(){            //on mouse over
  $(this).css("background-color", "red");    //check if selected
  var myVariable = $(this).attr("class");                  //then place css into variable
  alert(myVariable);  
}).mouseleave(function() {               //..and when I leave it
      $( this ).removeAttr( "style" );       //remove color
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="tile 11">div 1</div>
<div class="tile 35">div 2</div>
<div class="tile 89">div 3</div>