2014-04-22 44 views
13

请帮忙。jquery addClass()不能与event.target配合使用

为什么jquery addClass()不能与event.target一起使用? 我已经做了一个代码,它应该点击目标时添加类,但它不起作用,它说,e.target.addClass是不是一个函数。

http://jsfiddle.net/Lq9G4/

CODE:

<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Class Test</title> 
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
    <style> 
     .big { 
      font-size: 5em; 
     } 
     .small { 
      font-size: 1em; 
     } 
    </style> 

</head> 
<body> 
    <p>This is the text</p> 
    <script> 
     $(function() { 
      $("p").click(function(e) { 
         $("a").removeClass("big").addClass("small"); 
         $("this").addClass("big"); //This doesn't work 
         e.target.addClass("big"); //nor this one     
        }); 
     }); 

    </script> 
</body> 
</html> 

回答

24

基本上e.target将是一个javascript对象,你必须把它转换成一个Jquery对象利用像.addClass()

尝试它的功能之前,

$(e.target).addClass("big"); 

并且与此同时$("this").addClass("big");此代码将不起作用,因为您将this作为字符串传递。 this也是一个JavaScript对象,你需要太转换,作为一个jQuery对象像$(this)

+0

哇。有用!这是为什么? – qtgye

+1

@ user3540736我已经在我的答案中给出了一些解释.. :) –

+0

现在对我来说很清楚。非常感谢! :) – qtgye

1

改变这一行

$("this").addClass("big"); //This doesn't work 

$(this).addClass("big"); //This will work work 

,并且,如果你与event本身需要它那么你可以使用

$(e.target).addClass('big'); 
2

由于.addClass()是一个jQuery方法,你需要一个jQuery对象,所以通过包装这里面$转换e.target到jQuery对象:

$(e.target).addClass("big"); 

在那旁边,另一个解决方案是使用$(this)。你不需要换this" "

$(this).addClass("big"); 

Updated Fiddle

0

试试这个:

$(e.target).addClass('big'); 

Demo

2

你有ŧ WO问题:

$(this).addClass("big"); //Unquote to "this" 
$(e.target).addClass("big"); // select e.target with $() wrapper. 
0
<script> 
    $(function() { 
     $("p").click(function(e) { 
        $("a").removeClass("big").addClass("small"); 
        $(this).addClass("big"); //This doesn't work    
       }); 
    }); 

</script> 

“这个”=>此

相关问题