【发布时间】:2020-03-22 13:27:50
【问题描述】:
我想要做的是使用我成功存储在 LocalStorage 中的值。根据选择的颜色,该颜色的值将保存在 LocalStorage(红色、绿色或蓝色)中。我的问题是,我现在如何使用这些值来保存这些单独按钮的背景颜色以供下次使用?任何帮助将不胜感激!
代码运行链接:https://jsfiddle.net/Lzj3g86f/7/
// Creates a Popover
$("[data-toggle=popover]").popover({
html: true,
sanitize: false,
trigger: 'focus',
content: function(){
return $('#popover-content').html();
}
});
// Target the Button That is Clicked
var targetBtn;
$('.myBtn').each((i, item) =>{
$(item).click((e) =>{
targetBtn = e.target;
});
});
// Set the Color of the Buttons
function setColor(c){
var i = $(targetBtn).index();
$(targetBtn).css("background", saveColorPref(i, c));
}
// Creates Data items inside LocalStorage
var saveColorPref = (i, c) =>{
localStorage.setItem("color-" + i, c);
return c;
}
// Retrieves Data items From LocalStorage
var getColorPref = (i) =>{
return localStorage.getItem("color-" + i) || "";
}
/*
Now i want to make use of the Stored Values so that the picked colors
for the buttons will be saved for next time. I understand how to store text in the LocalStorage,
but how can I now use these values to save the background-color of these individual buttons?
*/
.popover-content{
display: flex;
justify-content: space-around;
align-items: center;
background: #efefef;
width: 230px;
height: 80px;
}
.close{
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
position: absolute;
top: 0px;
left: 210px;
}
.close:hover,
.close:focus{
color: #000;
text-decoration: none;
cursor: pointer;
transition: 0.5s;
}
.myBtn{
background-color: #DCDCDC;
border: 0.5px solid #808080;
color: white;
width: 30px;
height: 30px;
border-radius: 6%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.demo1,.demo2,.demo3{
border: none;
color: white;
width: 60px;
height: 60px;
border-radius: 50%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.demo1{
background-color: red;
}
.demo2{
background-color: green;
}
.demo3{
background-color: blue;
}
.hide{
display: none;
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<body>
<button class="myBtn" data-toggle="popover" data-placement="bottom" data-html="true">1</button>
<button class="myBtn" data-toggle="popover" data-placement="bottom" data-html="true">2</button>
<div id="popover-content" class="hide">
<button class="demo1" onClick="setColor('red')">Red</button>
<button class="demo2" onClick="setColor('green')">Green</button>
<button class="demo3" onClick="setColor('blue')">Blue</button>
<span class="close">×</span>
</div>
</body>
</body>
【问题讨论】:
-
你如何“识别”每个按钮?索引不是记住按钮的好方法。它使您的代码难以维护。如果您可以设置 ID 或唯一的类名或名称,这是可以实现的。现在您可以将“标识符”和“颜色偏好”存储在本地存储中,并在加载期间检索它。
标签: javascript jquery local-storage bootstrap-popover