如何使用jQuery3的hasClass来实现切换DIV的背景颜色或者图片
问题描述:
在jQuer1.8的和环境下我用 toggle方法实现了切换DIV的背景图片,但在JQuery3里发现不能使用了,之后查找资料学习了一下用hasClass方法来实现,下面是我写的代码,但是没有效果,请大佬们帮我看一下是哪里的问题。
我的思路是写出两个CSS样式,然后通过点击来判断。
运行后发现不能实现,点击以后没有反应,不知道问题出在哪里。
Jquery刚刚开始学习,很多东西都还不太明白。望指教!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
.picture1 {
height: 50px;
width: 50px;
background: red;
}
.picture2 {
height: 50px;
width: 50px;
background: yellow;
}
</style>
<script type="javascript">
$(document).ready(function(){
$('.picture1').click(function () {
if ($(".picture1").hasClass('picture1')) {
$(".picture1").addClass('picture2').removeClass('picture1');
} else {
$(".picture1").addClass('picture1').removeClass('picture2');
}
});
})
</script>
</head>
<body>
<div class="picture1"></div>
</body>
</html>
答
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
.picture1 {
height: 50px;
width: 50px;
background: red;
}
.picture2 {
height: 50px;
width: 50px;
background: yellow;
}
</style>
<script src="jquery-3.4.1.js"></script>
<script>
$(function() {
$('div').click(function () {
if ($(".picture1").hasClass('picture1')) {
$(".picture1").addClass('picture2').removeClass('picture1');
} else {
$("div").addClass('picture1').removeClass('picture2');
}
});
})
</script>
</head>
<body>
<div class="picture1"></div>
</body>
</html>