【问题标题】:Chrome.storage for "new tab" chrome app; remembering checkboxesChrome.storage 用于“新标​​签”chrome 应用程序;记住复选框
【发布时间】:2018-10-27 15:42:17
【问题描述】:

我对编程很陌生,但渴望学习。我正在尝试创建一个跟踪目标的应用程序(我不喜欢我找到的那些,所以我想自己制作)。无论如何,有要检查的复选框,当我稍后打开一个新选项卡时,我希望选中复选框。这是我的代码中的一个小sn-p:

<label class="container">Drink 2 liters of water
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>

如何使用chrome.storage 函数记住我点击了这个框?感谢您的帮助!

【问题讨论】:

    标签: javascript html css google-chrome-app


    【解决方案1】:

    在较高级别上,您需要在任何时候单击复选框或单击按钮时使用chrome.storage 来保存您的更改。

    如果您想在每次单击复选框时保存,您需要将侦听器绑定到复选框的更改事件。然后,调用 chrome.storage 保存。

    document.querySelectorAll('input[type="checkbox"]').forEach(elem=>{ //Get all input checkboxes
        elem.addEventListener('change',(event)=>{ //Add a change listener
            const key = event.target.name; //get the name value from the input element
            const value = event.target.checked; // has it been checked?
            chrome.storage.local.set({[key]: value}, ()=>  { //save it
                console.log('Value is set to ' + value);
            });
        })
    })
    

    按下按钮时的保存将是类似的。您将单击侦听器绑定到按钮,然后在回调中,选择所有复选框并循环保存。

    页面加载后,您需要获取所有保存的值,并设置检查状态。

    chrome.storage.local.get(['goal1','goal2'],(results)=>{ //Fetch goal1, goal2, goalN... from chrome.storage
        //.get returns a keyed object you can loop over.
        Object.keys(results).forEach((goal)=>{ 
            //Set the check state of each goal.
            document.querySelector(`input[name="${goal}"]`).checked = results[goal];
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 2014-02-04
      • 2011-07-28
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      相关资源
      最近更新 更多