jQuery addClass()无法与event.target一起使用 [英] jquery addClass() not working with event.target

查看:500
本文介绍了jQuery addClass()无法与event.target一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助.

为什么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>

解决方案

基本上,e.target将是一个javascript对象,您必须先将其转换为Jquery对象,然后才能使用其像.addClass()这样的功能

尝试

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

同时,由于您将this作为字符串传递,因此$("this").addClass("big");此代码将不起作用. this也是一个javascript对象,您也需要将其转换为类似于$(this)

的jquery对象

Please help.

Why is the jquery addClass() not working with event.target? I have made a code and it supposed to add class on the target when clicked, but it does not work, and it says,e.target.addClass is not a function.

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>

解决方案

Basically e.target will be a javascript object, you have to convert it into a Jquery object before utilizing its functions like .addClass()

Try,

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

and at the same time, $("this").addClass("big"); this code will not work since you are passing this as a string. this also a javascript object, you need to convert that too as a jquery object like $(this)

这篇关于jQuery addClass()无法与event.target一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆