出于维护目的,我只是想使用 ID 而不是索引来更改按钮的背景颜色。有什么建议如何做到这一点吗?
从 jsfiddle 运行代码:https ://jsfiddle.net/p6kuf0zv/4/
或者查看代码片段中的代码:
// On click on a button, a popover menu will show up
$("[data-toggle=popover]").popover({
html: true,
sanitize: false,
trigger: 'focus',
content: function() {
return $('#popover-content').html();
}
});
// Creates data items inside local storage with keyName and keyValue
var saveColorPref = (keyName, keyValue) => {
localStorage.setItem(keyName, keyValue);
return keyValue;
}
// Retrieves data items from local storage
var getColorPref = (keyName) => {
return localStorage.getItem(keyName);
}
// How can the code bellow be changed to make use of ID instead of index?
var targetBtn;
function setColor(keyValue) {
var keyName = $(targetBtn).index();
console.log(keyName, keyValue);
$(targetBtn).css("background", saveColorPref(keyName, keyValue));
}
$('.myBtn').each((keyName, item) => {
$(item).click((e) => {
targetBtn = e.target;
});
});
.demo1{
background-color: red;
}
.demo2{
background-color: green;
}
.demo3{
background-color: blue;
}
<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>
肥皂起泡泡
相关分类