jquery - 读取文本文件? [英] jquery - Read a text file?

查看:39
本文介绍了jquery - 读取文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 html 文件,我想打开并从中读取,但我不完全确定该怎么做...基本上,它是一个相当大的文件 (big.html),并且,在单独的文件 (titles.html),我有一些 jquery 代码,我想用它来查找某些元素(即 h2 标签)并从这些标签中获取内部文本并将该文本写入 titles.html...我不确定,特别是如何打开一个单独的文件并从中读取,其次,我不确定下面的代码在获取 h2 标签中的文本时是否有效......

I have an html file that I'd like to open and read from, but I'm not entirely sure how to do that... Basically, it's a fairly large file (big.html), and, in a separate file (titles.html), I have some jquery code that I'd like to use to find certain elements (namely, h2 tags) and get the inner text from those tags and write just that text to titles.html... I'm not sure, particularly, how to open a separate file and read from it, and secondly, I'm not sure if the code below will work when it comes to getting the text within the h2 tags...

$(document).ready(function() {
    $("h2").each(function() {
        var title = $(this).text();
        $("#mydiv").append(title);
    });
});

...

<div id="mydiv"></div>

我有点困惑如何用 jquery 做到这一点......我对整个事情很陌生,所以我什至不确定这是否可能......

I'm a bit confused how to do that with jquery... I'm pretty new to the whole thing, so I'm not even sure it's possible...

推荐答案

jQuery 提供方法 $.get 可以从 URL 中获取数据.因此,要读取"html/text 文档,需要通过 URL 访问它.获取 HTML 内容后,您应该能够将该标记包装为 jQuery 包装集并正常搜索.

jQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.

未经测试,但它的一般要点...

Untested, but the general gist of it...

var HTML_FILE_URL = '/whatever/html/file.html';

$(document).ready(function() {
    $.get(HTML_FILE_URL, function(data) {
        var fileDom = $(data);
        fileDom.find('h2').each(function() {
            alert($(this).text());
        });
    });
});

这篇关于jquery - 读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆