从外部HTML文档中收集DOM元素

时间:2010-04-29 12:36:20

标签: javascript dom

我正在尝试编写一个报告生成器来从外部HTML文件列表中收集用户注释。用户评论包含在<跨度>元件。

可以使用JavaScript完成吗?

这是我的尝试:

function generateCommentReport()
{
    var files = document.querySelectorAll('td a'); //Files to scan are links in an HTML table
    var outputWindow = window.open(); //Output browser window for report

    for(var i = 0; i<files.length; i++){
        //Open each file in a browser window
        win = window.open();
        win.location.href = files[i].href;

        //Scan opened window for 'comment's
        comments = win.document.querySelectorAll('.comment');
        for(var j=0;j<comments.length;j++){
            //Add to output report
            outputWindow.document.write(comment[i].innerHTML);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您需要在目标窗口上等待onload,然后才能阅读其文档中的内容。

comment是什么类型的元素?通常,您不能在任何元素上放置name。虽然可能会忽略诸如错放名称之类的未知属性,但您无法保证浏览器会将getElementsByName考虑在内。 (实际上,大多数浏览器,但IE没有。)class可能是更好的选择?

答案 1 :(得分:0)

每个Web浏览都在用户计算机上定义和控制的工作空间中工作,其中某些内容限制为像文件系统一样的代码 - 这些是安全标准,以确保来自Internet的恶意代码不会进入您的系统以防止存储的网络钓鱼敏感信息在它。只有在用户明确授予访问权限的情况下才允许使用Web浏览器。

But i can suggest you for Internet Application as

  - If List of commands is static then cache either by XML, Json or Cookies [it will store on user's system until it expires]
  - If dynamic then Ajax to retrieve it

答案 2 :(得分:0)

我想我有解决方案。

var windows = [];
var report = null;

function handlerFunctionFactory(i,max){
    return function (evt){
        //Scan opened window for 'comment's
        var comments = windows[i].document.querySelectorAll('.comment');

        for(var j=0;j<comments.length;j++){
            //Add to output report
            report.document.write(comments[j].innerHTML);
        }
        if((i+1)==max){
            report.document.write("</div></body></html>");
            report.document.close();
        }
        windows[i].close();
    }
}

function generateReport()
{
    var files = document.querySelectorAll('td a'); //The list of files to scan is stored as links in an HTML table
    report = window.open(); //Output browser window for report

    report.title = 'Comment Report';
    report.document.open();
    report.document.write('<!DOCTYPE html PUBLIC"-// W3C//DTD XHTML 1.0 Transitional//EN"" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
        + '<html><head><title>Comment Report</title>'
        + '</head><body>');

    for(var i = 0; i<files.length; i++){
        //Open each file in a browser window
        win = window.open();
        windows.push(win)
        win.location.href = files[i].href;
        win.onload = handlerFunctionFactory(i,files.length);
    }
}
  1. 欢迎任何重构提示。我并不完全相信工厂是将onload处理程序绑定到实例的最佳方法。
  2. 这仅适用于Firefox:(