2015-10-17 191 views
-1

我的页面上有一些元素。这些是他们中的一些:用Jquery选择类元素

<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 
}); 

但它没有工作。

例如,当我悬停第一个图块时,“myVariable”应该是“图块11”,但它不是。为什么?

+2

尝试'$(本).attr的''而不是$(本)( “类”).css' –

+1

@SandeepNayak真正奏效。非常感谢:) – Kajcioch

回答

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>

+1

这工作,非常感谢这么多家伙! ;)9分钟后接受你的答案 – Kajcioch