请帮忙。
为什么jqueryaddClass()
无法使用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").addClass("big");
由于您是this
作为字符串传递的,因此此代码将不起作用。this
也是一个javascript对象,您也需要将其转换为jquery对象,例如$(this)
您有两个问题:
$(this).addClass("big"); //Unquote to "this"
$(e.target).addClass("big"); // select e.target with $() wrapper.
e.currentTarget.classList.add("loading_arrow");
您可以使用上述代码通过js鼠标事件来添加loading_arrow类。
更改此行
$("this").addClass("big"); //This doesn't work
至
$(this).addClass("big"); //This will work work
而且,如果您event
本身需要它,则可以使用
$(e.target).addClass('big');
由于.addClass()
是jQuery方法,因此需要一个jQuery对象,因此可以e.target
通过将其包装在jQuery对象中来进行转换$
:
$(e.target).addClass("big");
除此之外,另一个解决方案是使用$(this)
。您不需要包装this
在内" "
:
$(this).addClass("big");
尝试这个:
$(e.target).addClass('big');
<script>
$(function() {
$("p").click(function(e) {
$("a").removeClass("big").addClass("small");
$(this).addClass("big"); //This doesn't work
});
});
</script>
“ this” =>这个
评论已关闭!