相当于标题所说的内容。
在控制台中,具有推送值的数组仅在眨眼间存在且无法被调用。这个数字是无关紧要的,只是现在试图推送到数组。
var storage = []
$('#submit').on('click', function(){
storage.push(5000000)
})
// Does this...
// console.log(storage) => []
// But I want this...
// console.log(storage) => [5000000]
答案 0 :(得分:1)
有效!
https://jsfiddle.net/buk2ment/1/
var storage = []
$('#submit').on('click', function(){
storage.push(5000000);
});
$('#submit1').on('click', function(){
console.log(storage);
});
如果您在点击事件失败后立即将输出放入控制台,因为您仅在点击后将值输入数组。
在您访问存储阵列后单击submit
按钮后,您将获得数组内的值,直到刷新页面为止。
检查上面的示例以获得清晰的图片。
答案 1 :(得分:0)
您可能正在使用点击事件但未阻止默认行为(即如果是链接)或提交表单(如果是提交输入类型)。
您的代码看起来正确但可能尝试添加event参数并调用其preventDefault()方法:
var storage = []
$('#submit').on('click', function(event){
event.preventDefault();
storage.push(5000000);
});
这会将数字添加到存储中,并且不会执行将刷新页面或转到其他位置的单击操作。通过这种方式,您可以继续向存储添加内容。
然后在调试器中点击几下后再执行console.log。
如果要保留存储中的数据但允许新页面加载,则需要查看html5存储功能,甚至使用cookie来存储数据。 HTML5存储将是最简单的。这是一个例子:
$(document).ready(function() {
if( storageAvailable('localStorage') ) {
$('.submit').on('click', function(e) {
// e.preventDefault();
var storage = localStorage.getItem('storage');
console.log(storage);
if( storage === null ) {
storage = [];
} else {
storage = JSON.parse(storage); // retrieve json data as an array not as the json string value we set it as later
}
storage.push(500000);
localStorage.setItem('storage', JSON.stringify(storage)); // store array as a string value as local storage only deals with strings
});
}
})
// taken from MDN site
function storageAvailable(type) {
try {
var storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return false;
}
}
您可以通过检索如下数据来获取控制台日志:console.log(localStorage.getItem('storage'));