如何使用Javascript在html文件中搜索字符串? [英] How to search for string in html files using Javascript?

查看:101
本文介绍了如何使用Javascript在html文件中搜索字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有5个html文件,我有一个搜索表单,我希望用它来搜索这些html文件中的文本。

I have 5 html files and I have a search form that I would like to use to search for text in these html files .

<form>
   <input type ='text' />
   <input type ='submit' />
</form>

我有一个使用xmlhttprequest获取文件的想法

I have an idea of using xmlhttprequest to get the files

var xhr = new XMLHttpRequest();
xhr.open("GET", "file1.html", false);
xhr.send();
var guid = xhr.responseText;

var xhr = new XMLHttpRequest();
xhr.open("GET", "file2.html", false);
xhr.send();
var guid = xhr.responseText;

...

然后在这些文件中搜索文本,但我不不知道如何使用javascript搜索文件。

then search for text in these files but I don't know how to search in the files using javascript.

如何在使用xmlhttprequest获取文件后搜索文件?或者有另一种方法来使用JavaScript进行搜索?

How to search the files after getting it using xmlhttprequest ? Or Is there is another way to do the search using javascript ?

推荐答案

首先,更改:

First, change:

<input type ='text' />

收件人:

<input id= 'text' type='text' />

然后,下面的代码将创建一个名为由文件组成的文件的数组。每个对象的'position'属性将包含'文件'内'文本'的位置,如果文本未找到,则为-1,如果文件未加载,则为-2。

Then, the code below will create an array called 'files' made up of objects. The 'position' property of each object will contain either the position of 'text' within 'filename', -1 if the text is not found, or -2 if the file did not load.

var text = document.getElementById('text' )

loadCount = 0;
files = [];
files[ 0 ] = {};
files[ 0 ][ 'filename' ] = "file1.html";
files[ 1 ] = {};
files[ 1 ][ 'filename' ] = "file2.html";
files[ 2 ] = {};
files[ 2 ][ 'filename' ] = "file3.html";
files[ 3 ] = {};
files[ 3 ][ 'filename' ] = "file4.html";
files[ 4 ] = {};
files[ 4 ][ 'filename' ] = "file5.html";

function search( item, index ) {

  xmlhttp.onload = function () {
    var files[ index ][ 'contents' ]  = xhr.responseText;
    if ( typeof files[ index ][ 'contents' ] !== 'undefined' ) {
      files[ index ][ 'position' ] = str.indexOf( text );
    } else {
      files[ index ][ 'position' ] = -2;
    }
    loadCount = loadCount + 1;
    if ( loadCount == 5 ) {
      // do whatever you want here
    }
  }

  var xhr = new XMLHttpRequest();
  xhr.open( "GET", item[ 'filename' ], false );
  xhr.send();

}

files.forEach( search );

这篇关于如何使用Javascript在html文件中搜索字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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