<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
div{
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
}
</style>
<script src="js/jquery-3.3.1.min.js"></script> <script>
jQuery(function(){
var $color='';
jQuery("button").click(function(){
$color=$(this).html();
});
$('div').click(function(){
$(this).css('background',$color);
});
});
</script>
<body>
<p>
<button>red</button>
<button>clear</button>
</p >
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
div{
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
}
</style>
<script src="js/jquery-3.3.1.min.js"></script> <script>
jQuery(function(){
var $color='';
jQuery("button").click(function(){
$color=$(this).html();
});
$('div').click(function(){
$(this).css('background',$color);
});
});
</script>
<body>
<p>
<button>red</button>
<button>clear</button>
</p >
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
$color=$(this).html();
改成下面这样就可以了,点击clear按钮就可以达到清除颜色的功能了
$color=$(this).html()=='red'?'red':'';
改一下就行了$color=$(this).html()=='clear'?'':$(this).html();