用于树视图的html,css和pure js

时间:2014-05-23 09:04:54

标签: html css jscript

这很简单,但我对JavaScript很新。这是我面临的问题。 我想有这个树视图:

Route (index.html)
  |--Tree 1 (tree1.html)
       |--Child 1 (tree1child1.html)
  |--Tree 2 (tree2.html)
       |--Child 1 (tree2child1.html)

每个html都会指向toggle.js来生成树视图。我对.js的问题是:如果我点击Tree 2,Child 1 - 它将显示正确的页面,但指向Tree 1,Child 1选项,因为该子项具有相同的名称。这是我使用的脚本。

function toggle(id) {
ul = "ul_" + id;
img = "img_" + id;
ulElement = document.getElementById(ul);
imgElement = document.getElementById(img);
if (ulElement) {
    if (ulElement.className == 'closed') {
        ulElement.className = "open";
        imgElement.src = "./menu/opened.gif";
    } else {
        ulElement.className = "closed";
        imgElement.src = "./menu/closed.gif";
    }
}
} // toggle()

function searchUp(element, tagName) {
// look through the passed elements
var current = element;
do {
    current = current.parentNode;
} while (current.nodeName != tagName.toUpperCase() && current.nodeName != "BODY");

return current.nodeName != tagName.toUpperCase() ? null : current;
}



function getAnchor(elements, searchText, exclude) {
     // look through the passed elements
     for (var i = 0; i < elements.length; i++) {
         if (elements[i].innerHTML == searchText) {
             if (exclude == null || exclude.innerHTML != elements[i].parentElement.innerHTML) {
                 // return the anchor tag
                 return elements[i];
             }
          }
         if (elements[i].children != null) {
             var a = getAnchor(elements[i].children, searchText, exclude);
             if (a != null) {
                 return a;
             }
         }
     }

     return null;
 }


function htmlEntities(str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g,          '&gt;').replace(/"/g, '&quot;');
 }

function select(tree) {
// NOTE: we need to escape the tree string to replace chevrons with their html equivalent in order to match generic strings correctly
var items = document.getElementById('menu').children;  // .getElementsByTagName("a");
var anchor = getAnchor(items, htmlEntities(tree[0]), null);
var ul = searchUp(anchor, "ul");
for (var i = 1; i < tree.length; i++) {
    anchor = getAnchor(ul.children, htmlEntities(tree[i]), anchor.parentElement);
    ul = searchUp(anchor, "ul");
}

if (anchor != null) {
    anchor.className = 'selected';
    if (ul.className != 'open') {
        toggle(ul.id.substr(3));
    }
}
} // select()

0 个答案:

没有答案