jQuery addClass()方法无法与event.target一起使用

22

请帮忙。

为什么jquery的addClass()在使用event.target时无法工作? 我已经编写了一段代码,当单击目标时应该添加类,但它不起作用,并且显示e.target.addClass不是一个函数。

http://jsfiddle.net/Lq9G4/

代码:

<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>
7个回答

46

基本上,e.target将是一个javascript对象,您需要将其转换为Jquery对象,然后再利用其函数,如.addClass()

尝试一下,

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

同时,$("this").addClass("big");这段代码无法正常工作,因为你将this作为字符串传递了。实际上this是一个Javascript对象,你需要将其转换为JQuery对象,像这样:$(this)


1
@user3540736,我在我的回答中已经给出了一些解释.. :) - Rajaprabhu Aravindasamy

3

您有两个问题:

$(this).addClass("big"); //Unquote to "this"
$(e.target).addClass("big"); // select e.target with $() wrapper.

2

更改此行

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

to

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

如果您需要与event本身一起使用,则可以使用以下代码:

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

2
<script>
    $(function() {
        $("p").click(function(e) {
                  $("a").removeClass("big").addClass("small");
                  $(this).addClass("big"); //This doesn't work               
                });
    });

</script>

"this"=>this


2

由于 .addClass() 是jQuery方法,您需要一个jQuery对象,因此请将 e.target 包装在 $ 内,将其转换为jQuery对象:

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

此外,另一个解决方案是使用$(this)。您不需要将this包装在" "中:
$(this).addClass("big");

更新的代码示例


2
    e.currentTarget.classList.add("loading_arrow");

你可以使用上面的代码行,在JS鼠标事件中添加loading_arrow类。

1

试试这个:

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

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接