[英]onchange to create autosave function (javascript) didn't work
Work by .click to save into localStorage: 通过单击以保存到localStorage:
$("check").onclick = function(){
parkArray = [check1,check2,check3,check4,check5];
localStorage.removeItem ("saveArray");
localStorage.setItem("saveArray",JSON.stringify(parkArray));
Didn't work by onchange to autosave into localstorage 通过onchange不能自动保存到本地存储中
parkArray = [check1,check2,check3,check4,check5];
parkArray.onchange = function () {
localStorage.removeItem ("saveArray");
localStorage.setItem("saveArray",JSON.stringify(parkArray));
Can anyone give advise how to solve this if I want Array autosaved when changed? 如果我想在更改后自动保存数组,谁能给出建议如何解决这个问题? Thank you.
谢谢。
Original link: https://github.com/erictsaiweb/card-parking/blob/master/cardpark.js 原始链接: https : //github.com/erictsaiweb/card-parking/blob/master/cardpark.js
You have to work with an callback function. 您必须使用回调函数。
// initalize
var parkArray = [check1,check2,check3,check4,check5];
// change
changeParkArray([check4,check5,check6,check7,check8], onChangeParkArray);
// change ahain
changeParkArray([check9,check10,check12,check21,check100], onChangeParkArray);
// the function who changes the array
function changeParkArray(newValue, callback){
parkArray = newValue;
callback(newValue);
}
// function to run after ParkArray is changed
function onChangeParkArray(data){
localStorage.removeItem ("saveArray");
localStorage.setItem("saveArray",JSON.stringify(data));
}
You cannot use the function onclick
on a jQuery object as it is meant for a JavaScript object (eg document.getElementById('element').onclick....
) it should be .click
or .on('click')
. 你不能使用该功能
onclick
,因为它是为一个JavaScript对象(例如一个jQuery对象上document.getElementById('element').onclick....
)应该.click
或.on('click')
And you're not targeting your element correctly, check
... Is it a class
or an id
... 而且您没有正确定位元素,
check
...是class
还是id
...
And onchange
does not exist in the array prototype. 并且
onchange
在数组原型中不存在。 It's only meant for DOM
object like input
and select
. 它仅用于
DOM
对象,例如input
和select
。
What you can do for the array is to check if the array parkArray
is the same as the one in localStorage
. 您可以对数组执行的操作是检查数组
parkArray
是否与localStorage
的数组相同。
eg 例如
$("#check").click(function(){
var saveArray = (localStorage.saveArray != undefined) ? JSON.parse(localStorage.saveArray) : [];
parkArray = [check1,check2,check3,check4,check5];
saveArray.forEach(function(v, i){
if(parkArray.indexOf(v) < 0){
localStorage.removeItem ("saveArray");
localStorage.setItem("saveArray",JSON.stringify(parkArray));
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.