vil*_*oui 5 javascript jquery indexeddb
在indexeddb上,我想查看是否有密钥permanent并执行某些操作.但如果没有,我想做一些其他的行动.如果permanent存在的话,我可以采取行动,但是当它不存在时,我可以让错误发挥作用.是onerror想去做这件事情?如何检查其中是否没有值?
var hashtype='permanent';
var getPermanent = store.get(hashtype);
getPermanent.onsuccess = function() {
var ivrame=getPermanent.result.value;
};
getPermanent.onerror = function() {
console.log('onerror')
};
Run Code Online (Sandbox Code Playgroud)
请参阅https://w3c.github.io/IndexedDB/#dom-idbobjectstore-get下的说明- 如果没有匹配的记录,该get方法将成功undefined.
所以你有几个选择:
get(key)并测试结果undefined.这是有效的,除非undefined您期望存储的值(它是有效值)count(key)- 如果存在则结果为1,如果不存在则结果为0.如果您只是为了存在而进行测试,那么很容易,但是不能为您提供记录.openCursor(key)和测试请求result是否是游标(记录存在request.result.value)或undefined(范围内没有记录)对于你的代码:
var hashtype='permanent';
// #1: Use get
var getPermanent = store.get(hashtype);
getPermanent.onsuccess = function() {
if (getPermanent.result === undefined) {
// no record with that key
} else {
var value = getPermanent.result;
}
};
// #2: Use count
var getPermanent = store.count(hashtype);
getPermanent.onsuccess = function() {
if (getPermanent.result === 0) {
// no record with that key
} else {
...
}
};
// #3: Use cursor
var getPermanent = store.openCursor(hashtype);
getPermanent.onsuccess = function() {
var cursor = getPermanent.result;
if (!cursor) {
// no record with that key
} else {
var value = cursor.value;
}
};
Run Code Online (Sandbox Code Playgroud)