如何将下面的代码编写为 jquery:
var imagefile = document.getElementsByClassName("fileImage");
var filename = imagefile.files[0];
我在下面尝试了这个,但它说它没有定义,即使我已经声明文件输入的类是“fileImage”。
var filename = $('.fileImage').files[0];
最佳答案
你不能直接执行imagefile.files[0]
因为
document.getElementsByClassName("fileImage")
//and
$('.fileImage')
返回一个“类似数组”的项目列表。 (AFAIK,getElementsBy*
函数,除了getElementsById
,返回一个NodeList
)
在获取 files[0]
之前,您需要先遍历它们。
对于纯 JS 方法:
for(var i=0; i < imagefile.length;i++){
var imgfile = imagefile[i];
//now imgfile is the DOM element itself
imgfile.files[0];
}
对于 jQuery,您链接 .each()
$('.fileImage').each(function(){
//"this" in here is the DOM element
this.files[0];
})
关于javascript - 如何将下面的代码编写为 jquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10220732/