将值还原到tokeninput字段-jQuery错误

时间:2018-07-11 23:53:35

标签: javascript jquery-tokeninput

我正在尝试从tokeninput字段中获取值,将其保存到本地存储,然后在以后检索它们。我收到一个错误。代码:

//Save to storage
 var selectedValues = $('#Contacts').tokenInput("get");
console.log(JSON.stringify(selectedValues));
localStorage.setItem('ContactsJSON', JSON.stringify(selectedValues));

//Restore
var names = localStorage.getItem("ContactsJSON");
console.log(names);
$.each(names, function (index, value) {
    $("#Contacts").tokenInput("add", value);
});

错误消息是:

  

无效的'in'操作数:预期的对象

jquery-1.10.2.js(1009,2)显示错误

我非常确定我的JSON是正确的,按照tokeninput docs,使用get API检索时,它应该采用正确的格式:

selector.tokenInput("get"); Gets the array of selected tokens from the tokeninput (each item being an object of the kind {id: x, name: y}).

我在本地存储中看到的数据如下:

[{id":59,"name":"Steve Carrell"},{"id":58,"name":"John Krasinski"},{"id":1,"name":"Jenna Fischer"}]

1 个答案:

答案 0 :(得分:1)

我相信您的问题是您正在获取字符串,而不是对象。

您应该从本地存储中对字符串调用JSON.pase()

因此,固定代码应类似于:

// here you are converting object to string:
localStorage.setItem('ContactsJSON', JSON.stringify(selectedValues));

var names = localStorage.getItem("ContactsJSON");
// here you should convert string back to object
var names_object = JSON.parse(names);
console.log(names_object);
$.each(names_object, function (index, value) {
    $("#Contacts").tokenInput("add", value);
});