Форум Flasher.ru

Форум Flasher.ru (http://www.flasher.ru/forum/index.php)
-   HTML/DHTML/CSS/JS/VB (http://www.flasher.ru/forum/forumdisplay.php?f=66)
-   -   DOM API (http://www.flasher.ru/forum/showthread.php?t=85201)

patience 18.09.2006 04:28

DOM API
 
Есть такой JS код

Код:

<head><title>Employee Data</title>
<script>
// This function loads the XML document from the specified URL, and when
// it is fully loaded, passes that document and the url to the specified
// handler function.  This function works with any XML document
function loadXML(url, handler) {
    // Use the standard DOM Level 2 technique, if it is supported
    if (document.implementation && document.implementation.createDocument) {
        // Create a new Document object
        var xmldoc = document.implementation.createHTMLDocument();
        // Specify what should happen when it finishes loading
        xmldoc.onload = function() { handler(xmldoc, url); }
        // And tell it what URL to load
        xmldoc.load(url);       
    }
    // Otherwise use Microsoft's proprietary API for Internet Explorer
    else if (window.ActiveXObject) {
        var xmldoc = new ActiveXObject("Microsoft.XMLDOM");  // Create doc.
        xmldoc.onreadystatechange = function() {              // Specify onload
            if (xmldoc.readyState == 4) handler(xmldoc, url);
        }
        xmldoc.load(url);                                    // Start loading!
    }
}

// This function builds an HTML table of employees from data it reads from
// the XML document it is passed.


function makeTable(xmldoc, url) {
    // Create a <table> object and insert it into the document.
    var table = document.createElement("table");
    table.setAttribute("border", "1");
    document.body.appendChild(table);

    // Use convenience methods of HTMLTableElement and related interfaces
    // to define a table caption and a header that gives a name to each column.
    var caption = "Employee Data from " + url;
    table.createCaption().appendChild(document.createTextNode(caption));
    var header = table.createTHead();
    var headerrow = header.insertRow(0);
    headerrow.insertCell(0).appendChild(document.createTextNode("Name"));
    headerrow.insertCell(1).appendChild(document.createTextNode("Job"));
    headerrow.insertCell(2).appendChild(document.createTextNode("Salary"));
   
    // Now find all <employee> elements in our xmldoc document
    var employees = xmldoc.getElementsByTagName("employee");   

    // Loop through these employee elements
    for(var i = 0; i < employees.length; i++) {         
       
        var e = employees[i];
        var name = e.getAttribute("name");
        var job = e.getElementsByTagName("job")[0].firstChild.data;
        var salary = e.getElementsByTagName("salary")[0].firstChild.data;

     
        var row = table.insertRow(i+1);
        row.insertCell(0).appendChild(document.createTextNode(name));
        row.insertCell(1).appendChild(document.createTextNode(job));
        row.insertCell(2).appendChild(document.createTextNode(salary));
    }
}
</script>
</head>
<body onload="loadXML(location.search.substring(1), makeTable)">
</body>

Запрос в браузере:
DisplayEmployeeData.html?data.xml

и получаем таблицу, информация которой из data.xml файла.

и есть код JS, практически, идентичный.., только ищёт td и small тэги в html файле....
Код:

<head><title></title>
<script>
// This function loads the HTML document from the specified URL, and when
// it is fully loaded, passes that document and the url to the specified
// handler function.  This function works with any XML document
function loadHTML(url, handler) {
    // Use the standard DOM Level 2 technique, if it is supported
    if (document.implementation && document.implementation.createDocument) {
        // Create a new Document object
        var htmldoc = document.implementation.createDocument("", "", null);       
        htmldoc.onload = function() { handler(htmldoc, url); }
        // And tell it what URL to load
        htmldoc.load(url);       
    }
    // Otherwise use Microsoft's proprietary API for Internet Explorer
    else if (window.ActiveXObject) {
        var htmldoc = new ActiveXObject("Microsoft.XMLDOM");  // Create doc.
        htmldoc.onreadystatechange = function() {              // Specify onload
            if (htmldoc.readyState == 4) handler(htmldoc, url);
        }
        htmldoc.load(url);                                    // Start loading!
    }
}

// This function builds an HTML table of employees from data it reads from
// the XML document it is passed.


function makeTable(htmldoc, url) {
    // Create a <table> object and insert it into the document.
    var table = document.createElement("table");
    table.setAttribute("border", "1");
    document.body.appendChild(table);
 
    var caption = "Sostav iz " + url;
    table.createCaption().appendChild(document.createTextNode(caption));
    var header = table.createTHead();
    var headerrow = header.insertRow(0);
    headerrow.insertCell(0).appendChild(document.createTextNode("Place"));
    headerrow.insertCell(1).appendChild(document.createTextNode("City"));
    headerrow.insertCell(2).appendChild(document.createTextNode("OnLine"));   
   
       
    var city = "", online="", place="";
    var tegs = htmldoc.getElementsByTagName("td");
    // Loop through these td elements
    for(var i = 0; i < tegs.length; i++) {       
        var t = tegs[i];
                 
        if(t.childNodes.length == 3)
          if(t.firstChild.nodeType == 3)
          {
              var infoT = t.firstChild.data; 
              if(info.substring(0,5)=="some text")
              city = t.getElementsByTagName("b")[0].fisrtChild.data;
          }   
    } 
    tegs = htmldoc.getElementsByTagName("small"); 
    for(var i = 0; i < tegs.length; i++) {       
        var s = tegs[i];           
        if(s.childNodes.length == 1)
        {
          if(s.firstChild.nodeType == 3)//Text Element
          {
              var infoS = s.firstChild.data; 
              if(infoS=="some text" || infoS=="some text")
              online = infoS;
          }
        }
        else
          if((s.childNodes.length == 2) && (s.lastChild.nodeType == 3)) 
          {
              place = s.lastChild.data;
          }
    }

        row.insertCell(0).appendChild(document.createTextNode(place));
        row.insertCell(1).appendChild(document.createTextNode(city));
        row.insertCell(2).appendChild(document.createTextNode(online));   
}
</script>
</head>

<body onload="loadHTML(location.search.substring(1), makeTable)">
</body>

...но работать отказываеться..., getElementsByTagName() возвращает пустой массив... => не хотит заходить в циклы...
файл передаваемый скрипту ?test.html точно содержит данные тэги (td и small)

Зарание благодарен за помощь.

KidsKilla 18.09.2006 17:23

нихрена не понятно.
1) локализуй проблему. типа в ворохе кода копаться не будет никто.
2) юзай библиотеки: http://jquery.com/
http://prototype.conio.net/ и т.п.


Часовой пояс GMT +4, время: 08:16.

Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.