简体   繁体   English

使用jQuery从通过FileReader上传的html文件中提取表格

[英]Extracting a table from html file uploaded via FileReader using jQuery

I am receiving a file uploaded using FileReader() ( e.target.result ) from which I need to extract the table. 我收到使用FileReader()e.target.result )上传的文件,我需要从中提取表。 From a normal html file this is easily done with $("table tbody") . 从普通的html文件中,可以使用$("table tbody")轻松完成此操作。 Is it possible to apply this on e.target.result without appending it to my document? 是否可以将其应用于e.target.result而不将其附加到我的文档中?

I am also open to other methods other than FileReader , but if possible I'd like to use this. 我也可以使用FileReader以外的其他方法,但是如果可能的话,我想使用它。

JsFiddle for practice: https://jsfiddle.net/Irikos/dega00u2/ 练习JsFiddle: https ://jsfiddle.net/Irikos/dega00u2/

You can use the DOMParser for this. 您可以为此使用DOMParser Just pass it your string with the type and it will give you an object you can treat the same way you treat the DOM. 只需将类型传递给您的字符串,它将为您提供一个对象,您可以像对待DOM一样对待它。 For example: 例如:

reader.onload = function() {
        parser=new DOMParser();
        var doc = parser.parseFromString(this.result, "text/html")
        // assumes table has some data element
        alert(doc.getElementById('data').innerHTML);
};

There's some docs here: https://developer.mozilla.org/en-US/docs/Web/API/DOMParser 这里有一些文档: https : //developer.mozilla.org/en-US/docs/Web/API/DOMParser

[See also: https://api.jquery.com/jquery.parsehtml/] [另请参见: https//api.jquery.com/jquery.parsehtml/]

I hope I understood what you're trying to do correctly, if you're getting the contents of the uploaded file as text, you can search that text directly and get the html tables from it using the following javascript lines: 希望我能理解您要正确执行的操作,如果您以文本形式获取上传文件的内容,则可以直接搜索该文本,并使用以下javascript行从中获取html表:

var pattern = /(<table)([\s\S]+?)(\/table>)/gim
var theTablesInAnArray = e.target.result.match(pattern);

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

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