出于维护目的,我只是想使用 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>
1 回答
肥皂起泡泡
TA贡献1829条经验 获得超6个赞
回应:
如何使用 id 而不是索引来定位按钮?
更改setColor函数如下图所示:
前:
function setColor(keyValue) {
var keyName = $(targetBtn).index();
console.log(keyName, keyValue);
$(targetBtn).css("background", saveColorPref(keyName, keyValue));
}
后:
function setColor(keyValue) {
var keyName = $(targetBtn).attr('id');
console.log(keyName, keyValue);
$(targetBtn).css("background", saveColorPref(keyName, keyValue));
}
SO 片段抛出此错误:
Uncaught DOMException: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.
所以你看不到按钮颜色的变化。但这在你的 jsfiddle 中有效。
- 1 回答
- 0 关注
- 87 浏览
添加回答
举报
0/150
提交
取消