jQuery addClass()无法与event.target一起使用 [英] jquery addClass() not working with event.target
问题描述
请帮助.
为什么jQuery addClass()
无法与event.target
一起使用?
我已经编写了一个代码,它应该在单击时在目标上添加类,但是它不起作用,并且说e.target.addClass
不是函数.
代码:
<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)
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.
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屋!