【问题标题】:Unexpected string from Chrome storage setChrome 存储集中的意外字符串
【发布时间】:2013-11-10 22:20:55
【问题描述】:

在检查密钥是否已存在后,我正在尝试在 localStorage 中设置,但出现此错误。有谁知道发生了什么,我该如何解决?

chrome.storage.sync.get($div.attr('id'),function(items){
    var lastError = chrome.runtime.lastError;
    if (lastError) console.log($div.attr('id')+" does not exist.\n", lastError);
    else chrome.storage.sync.set({$div.attr('id'):$div.html()}, function(){}); //I'm having the error from this line
});

Uncaught SyntaxError: Unexpected string

编辑: 显然这与 attr('id')
因为我创建了一个变量,然后问题就消失了。还是谢谢你。
这是有效的:

var myobj = {}, key = $div.attr('id');
myobj[key] = $div.html();
chrome.storage.sync.get(key,function(items){
    var lastError = chrome.runtime.lastError;
    if (lastError) console.log(key+" does not exist.\n", lastError);
    else chrome.storage.sync.set(myobj, function(){}); //The error is gone
});

【问题讨论】:

  • 对你更新的 sn-p 来说只是一个小小的 nit(对不起,如果我说的是显而易见的):你可能想将你的 var 移动到最顶部并在你仍然存在的 2 个地方使用它有 $div.attr('id')。
  • 注意问题,报告的编辑版本工作不会出错,但它使用文字键“key”存储数据,而不是从 div 获取的 id 属性。
  • 是的,两者可能都是正确的,我会用我的最新代码更新。

标签: javascript local-storage google-chrome-app


【解决方案1】:

问题不在于attr 本身,而在于您尝试使用它在新对象文字上动态设置键的方式:

{$div.attr('id'):$div.html()}

您不能以这种方式创建对象字面量。创建对象字面量的键必须是字符串或数字字面量。

要将动态键附加到对象,您宁愿执行以下操作:

else {
  var obj = {}, key = $div.attr('id');
  obj[key] = $div.html();
  chrome.storage.sync.set(obj, function(){});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多