使用Jquery选择类元素

时间:2015-10-17 11:02:53

标签: javascript jquery html css

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

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

我希望在我悬停它的时候有一小部分元素进入变量。

我试过

$(".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
});

但它没有用。

例如,当我悬停第一个图块时,“myVariable”应该是“图块11”,但事实并非如此。为什么呢?

1 个答案:

答案 0 :(得分:1)

这很容易。您需要使用$(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>

相关问题