Javascript 函数应该返回对象,但它';s返回为未定义
我尝试获取函数返回的图像宽度和高度,但每次都返回为未定义,如果在函数中显示console.log值,则每次都返回未定义 我怀疑的主要问题是作用域,因为它是一个嵌套函数,但我不确定是否是这样 JS代码Javascript 函数应该返回对象,但它';s返回为未定义,javascript,jquery,function,nested,Javascript,Jquery,Function,Nested,我尝试获取函数返回的图像宽度和高度,但每次都返回为未定义,如果在函数中显示console.log值,则每次都返回未定义 我怀疑的主要问题是作用域,因为它是一个嵌套函数,但我不确定是否是这样 JS代码 //get image width and height $(document).ready(function(){ //object method function dimensions($width, $height){ this.getWid
//get image width and height
$(document).ready(function(){
//object method
function dimensions($width, $height){
this.getWidth = $width;
this.getHeight = $height;
}
//gets image data
function readURL(input) {
var reader = new FileReader();
var image = new Image();
reader.onload = function (e) {
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
return image;
}
//gets image dimensions (width height)
function getImageDimensions($img){
var $dimensions;
$img.onload = function(){
$dimensions = new dimensions($img.width, $img.height);
}
return $dimensions;
}
$("#imgInp").change(function(){
alert(getImageDimensions(readURL(this)));
});
});
<form id="form1" runat="server">
<input type='file' id="imgInp" accept="image/*"/>
</form>
Html代码
//get image width and height
$(document).ready(function(){
//object method
function dimensions($width, $height){
this.getWidth = $width;
this.getHeight = $height;
}
//gets image data
function readURL(input) {
var reader = new FileReader();
var image = new Image();
reader.onload = function (e) {
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
return image;
}
//gets image dimensions (width height)
function getImageDimensions($img){
var $dimensions;
$img.onload = function(){
$dimensions = new dimensions($img.width, $img.height);
}
return $dimensions;
}
$("#imgInp").change(function(){
alert(getImageDimensions(readURL(this)));
});
});
<form id="form1" runat="server">
<input type='file' id="imgInp" accept="image/*"/>
</form>
有人能解释一下为什么它不返回对象,但返回未定义的对象吗?这是因为在DOM中渲染之前,图像没有宽度或高度。 因此,将实例放在onload处理程序中是正确的。 问题是,处理程序仅在图像加载时触发,但在加载之前执行返回行。 换句话说,执行这一行
return $dimensions;
在此函数之前
$img.onload = function(){
$dimensions = new dimensions($img.width, $img.height);
}
将报税表以$img.onload的形式显示,如下所示:
$img.onload = function(){
return new dimensions($img.width, $img.height);
}
如果我在getImageDimensions($img)函数中对$img.width和$img.height发出警报,图像宽度和高度将被警报。是的,我编辑了我的回答。出于某种原因,它仍然返回未定义。