jQuery实现div单选与多选
一、单选
1、思想:
先监听所有的div,点击某个div触发事件。如果被点击的div的border是红色,则remove;否则被点击的div的border不是红色,则遍历所有的div,去掉所有的div的红色border,点击了某个div,再给某个加上border。
2、js代码
js代码如下:
$(".container").on("click",this,function () {
if($(this).hasClass("redBorder")){
$(this).removeClass("redBorder");
}
else{
$(".container").each(function () {
$(this).removeClass("redBorder");
})
$(this).addClass("redBorder");
}
})
3、完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div单选</title>
<style>
.container{
width: 100px;
height: 100px;
background-color: #E6E6E6;
border:1px solid #cccccc;
text-align: center;
line-height: 100px;
float: left;
margin-left: 20px;
}
.redBorder{
border: 1px solid red;
}
</style>
<script src="jquery-2.2.4.js" type="text/javascript"></script>
</head>
<body>
<div class="box">
<div class="container">DIV</div>
<div class="container">DIV</div>
<div class="container">DIV</div>
</div>
</body>
<script>
$(".container").on("click",this,function () {
if($(this).hasClass("redBorder")){
$(this).removeClass("redBorder");
}
else{
$(".container").each(function () {
$(this).removeClass("redBorder");
})
$(this).addClass("redBorder");
}
})
</script>
</html>
4、选中状态下点击,则去掉选中;未选中状态点击则变成唯一选中状态
二、多选
1、思想:
利用addClass()、removeClass()和toggleClass()函数进行多选。
2、js代码:
$(".container").on("click",this,function () {
$(this).toggleClass("redBorder");
})
3、完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div单选</title>
<style>
.container{
width: 100px;
height: 100px;
background-color: #E6E6E6;
border:1px solid #cccccc;
text-align: center;
line-height: 100px;
float: left;
margin-left: 20px;
}
.redBorder{
border: 1px solid red;
}
</style>
<script src="jquery-2.2.4.js" type="text/javascript"></script>
</head>
<body>
<div class="box">
<div class="container">DIV</div>
<div class="container">DIV</div>
<div class="container">DIV</div>
</div>
</body>
<script>
$(".container").on("click",this,function () {
$(this).toggleClass("redBorder");
})
</script>
</html>