function changecolor(event) {
document.querySelector(".selected").classList.remove("selected");
event.classList.add("selected");
}
.btn-default.selected {
background: #2f9734;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class=" btn btn-default selected" data-spid="2bhk" onclick="changecolor(this)">Default 1</div>
<div class="btn btn-default" data-spid="3bhk" onclick="changecolor(this)">Default 2</div>
<div class="btn btn-default" data-spid="4bhk" onclick="changecolor(this)">Default 3</div>
<div class="btn btn-default" data-spid="5bhk" onclick="changecolor(this)">Default 4</div>
<div class="btn btn-default" data-spid="6bhk" onclick="changecolor(this)">Default 5</div>
</div>
</body>
</html>
此代码是一个原型。
我无法更改changecolor
函数,并且新的HTML更改可以通过JavaScript进行。现在,如何获取先前选择的状态。实际上,我想要上一个选择的按钮的data-spid
。
答案 0 :(得分:1)
function changecolor(event)
{
document.querySelector(".selected").classList.remove("selected");
event.classList.add("selected");
}
var spids = ['2bhk'];
$(document).ready(function() {
$(".btn").click(function(element) {
spids.push($(".selected").attr('data-spid'));
if(spids.length-2>=0){
console.log('previously selected: ' + spids[spids.length - 2]);
}
});
});
.btn-default.selected
{
background:#2f9734;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class=" btn btn-default selected" data-spid="2bhk" onclick="changecolor(this)">Default 1</div>
<div class="btn btn-default" data-spid="3bhk" onclick="changecolor(this)">Default 2</div>
<div class="btn btn-default" data-spid="4bhk" onclick="changecolor(this)">Default 3</div>
<div class="btn btn-default" data-spid="5bhk" onclick="changecolor(this)">Default 4</div>
<div class="btn btn-default" data-spid="6bhk" onclick="changecolor(this)">Default 5</div>
</div>
</body>
</html>
答案 1 :(得分:0)
您只需实例化一个初始值为'2bhk'的变量,然后在调用changeColor()时对其进行更新。
var previousSpid="2bhk";
function changecolor(event){
document.querySelector(".selected").classList.remove("selected");
event.classList.add("selected");
previousSpid = $(".selected").attr('data-spid')
}