简体   繁体   English

document.getElementById的工作原理是什么,但jquery没有?

[英]What's the reason that document.getElementById works but jquery doesn't?

This question might seem elementary to some but I can't get my head around it. 对于一些人来说,这个问题可能看起来很简单,但我无法理解它。 I am working on a XMLHttpRequest Ajax file upload. 我正在处理XMLHttpRequest Ajax文件上传。 the first step is to selected the fileUpload element that is on my page and for some reason javascript works but not query, here's the following two lines: 第一步是选择我页面上的fileUpload元素,由于某种原因javascript工作但不查询,这里有以下两行:

var fileInput = $('#the-file'); //doesn't work
var fileInput = document.getElementById('the-file'); //works

do I have to specify a method after the jquery selector or sth? 我必须在jquery选择器之后指定一个方法吗? Because I can't see why else it wouldn't work, aren't they practically the same code? 因为我不明白为什么它不起作用,它们实际上是不是相同的代码?

I have added the jquery.js file on top (I have many lines of jquery working on other parts of my file so that can't be the issue.) and the document ready. 我在顶部添加了jquery.js文件(我的文件的其他部分有很多jquery工作,所以这不是问题。)并准备好文档。 I got it to work but am wondering the reason behind this. 我得到了它的工作,但我想知道这背后的原因。

Edit 编辑

By doesn't work I mean that with the jquery selector I get "undefined" in console log but with the javascript I get all the file information that I need. 通过不起作用我的意思是使用jquery选择器我在控制台日志中得到“未定义”但是使用javascript我得到了我需要的所有文件信息。

The problem is that the jQuery object is a wrapper for the actual DOM object - which in this case is an HTML <input> element which has the type file . 问题是jQuery对象是实际DOM对象的包装器 - 在这种情况下是具有类型file的HTML <input>元素。 Only the actual DOM object has the files property, not the jQuery object. 只有实际的DOM对象具有files属性,而不是jQuery对象。 You can access the DOM elements referenced by using numeric indexes, which will only be 0 in this situation. 您可以使用数字索引访问引用的DOM元素,在这种情况下只能为0。 Therefore, this is the solution: 因此,这是解决方案:

var fileInput = $('#the-file');
fileInput.files[0]; // TypeError: cannot read property '0' of undefined
fileInput[0].files[0]; // works

Of course, the jQuery way of doing it would be to use the prop() function, which gets the property of the first DOM object in the jQuery object: 当然,jQuery的做法是使用prop()函数,它获取jQuery对象中第一个DOM对象的属性:

fileInput.prop('files')[0];

Given that I don't know what you mean by "doesn't work" I would guess that its because whatever is using fileInput wants a DOM element and not a jquery object. 鉴于我不知道你的意思是“不起作用”我猜它是因为无论使用什么文件输入想要一个DOM元素而不是一个jquery对象。 Try this: 尝试这个:

var fileInput = $('#the-file')[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM