javascript - 如何将下面的代码编写为 jquery?

标签 javascript jquery

如何将下面的代码编写为 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/

相关文章:

javascript - 在maven Spark java应用程序中运行html文件

javascript - 用于匹配 CSV 字段值内的引号的正则表达式

javascript - jsPDF addHTML 获取滚动元素的全部内容

javascript - 将矩阵输出文本更改为西里尔文 unicode 脚本

javascript - 每当组件加载到 DOM 时,Knockout.js 回调

javascript - jQuery serialize() 排除 div.classname 中的所有元素

javascript - Jquery 表插件

javascript - 使用 jquery 时 DOM 操作在 Angular 上很慢

javascript - 将提交按钮从 "button"更改为 "submit"破坏了我的 Google Apps 脚本

javascript - 按下回车键时 Preventdefault 不起作用