[英]Chrome Extension set storage value on checkbox click
我正在使用Google Chrome擴展程序進行工作,該擴展程序使用contentscripts來隱藏,移動和以其他方式更改當前頁面的元素。 我正在處理一個頁面,其中有一些要更改的元素,因此我為每個元素設置了storage.sync值。 由於每個選項都會產生巨大變化,因此我在彈出窗口中為每個選項進行了切換。 我試圖讓每個復選框使用jQuery(特別是jQuery.click和jQuery.each)將復選框ID的storage.sync值設置為復選框的布爾值。 我的彈出窗口的html是:
<html>
<head>
<title>Options</title>
<script src="jquery-3.1.1.min.js"></script>
<script src="popup.js"></script>
</head>
<body style="width: 400px">
<h3>Settings</h3>
<input class="option" id="opt1" type="checkbox">Option 1.</input><br>
<input class="option" id="opt2" type="checkbox">Option 2.</input><br>
<input class="option" id="opt3" type="checkbox">Option 3.</input>
<button id="other">TBI</button>
</body>
</html>
其中'jquery-3.1.1.min'是縮小的jQuery源,而popup.js是:
$(document).ready(function() {
$('.option').each(function(index, elem) {
chrome.storage.sync.get(elem.id, function (value) {
elem.checked = value.fix;
});
elem.change(function() {
chrome.storage.sync.set({this.id: this.checked);
});
});
});
我還嘗試用從elem
到$(this)[0]
以及$(elem)
所有內容替換this
,但是每次遇到不同來源的錯誤時,都可以使用。 通常, elem
會產生Uncaught SyntaxError: Unexpected token .
this
產生Uncaught SyntaxError: Unexpected token this
。
為什么會發生這種情況? 如何避免這種情況? 我主要是python編碼器,所以我希望我誤解了每個值的范圍或this
的含義。 我不明白的是,它如何轉化為Unexpected token
錯誤。 謝謝!
this.id
是對象文字中的無效鍵。 {[this.id]: this.checked}
。 var o = {}; o[this.id] = this.checked;
var o = {}; o[this.id] = this.checked;
}
。 chrome.storage
是異步的,因此在實際獲取值之前會附加elem.change
,這可能並不是您真正想要的。 但是,在這種情況下,這沒什么大不了的:您只需將相同的值寫回到chrome.storage。 最好通過提供一組鍵一次讀取所有值:
chrome.storage.sync.get( $('.option').map((i, el) => el.id), data => { $.each(data, (id, value) => $(`#${id}`)[0].checked = value); $('.option').change(function() { chrome.storage.sync.set({[this.id]: this.checked}); }); } );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.