javascript 怎样把闭包里处理得到值传到闭包外面,使闭包外面的变量af的值和闭包里af的值同步变化、相等?
HTML code
<!DOCTYPE HTML>
<html>
<head>
<title>Canvas </title>
<style type="text/css">
.thumb {
height: 75px;
border: 5px solid #000;
margin: 20px 10px 0 0;
}
</style>
</head>
<body>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
var af = 2;//闭包外的af
document.getElementById('files').addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = function test(e) {
var df = 60;
var dataUri = event.target.result;
af = 10 + df + i; //闭包里的af
img = new Image();
img.src = dataUri;
document.body.appendChild(img);
alert(af);// 弹出闭包里af的值
}
reader.readAsDataURL(f);
}
alert(af); //弹出闭包外的af的值
}
</script>
</body>
</html>
怎样把闭包里处理得到值传到闭包外面,使闭包外面的变量af的值和闭包里af的值同步变化、相等??
------解决方案-------------------- function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var testAf = this;
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = function test(e) {
var df = 60;
var dataUri = event.target.result;
// af = 10 + df + i; //闭包里的af
testAf.af = 10 + df + i;
img = new Image();
img.src = dataUri;
document.body.appendChild(img);
alert(testAf.af);// 弹出闭包里af的值
}
reader.readAsDataURL(f);
}
alert(af); //弹出闭包外的af的值
}
你试试看行不行
------解决方案--------------------
<!DOCTYPE HTML>
<html>
<head>
<title>Canvas </title>
<style type="text/css">
.thumb {
height: 75px;
border: 5px solid #000;
margin: 20px 10px 0 0;
}
</style>
</head>
<body>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
var af = 2;//闭包外的af
document.getElementById('files').addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
// var reader = new FileReader();
var canvas = document.createElement("canvas");
var dataUri = canvas.toDataURL("image/png");
}
alert(af); //弹出闭包外的af的值
}
</script>
</body>
</html>
其实你可以用其它方法来把onload事件取代吧!这样会变得简单多了....