我有这个脚本,我认为它比较简单。它基本上制作了 iframe 内容的树状布局。当树的部分悬停时,它们对应的 iframe 元素被“选中”。但它不工作,为我的生活。这是一些快速的半伪代码:
function traverseTree(c,o){
//c = the tree subset to put more stuff in
//o = the element to traverse
var treeNode = D.createElement('div');
c.appendChild(treeNode);
treeNode.innerHTML = o.tagName;
treeNode['refNode'] = o;
treeNode.addEventListener('mouseover',check,false);
loop(o.children){
traverseTree(treeNode,o.child);
}
}
function check(e){
alert(e.target.refNode);
}
e.target.refNode 出现问题。它只给出第一个节点(或 HTML 标记)的元素引用。其余的未定义。但是,当我在设置后立即检查 treeNode.refNode 时,它总是正确的。
编辑:
所以,我做了一个快速测试:
<html>
<head>
<title>Test</title>
<script>
window.onload = function(){
createTree(document.getElementById('tree'),
document.getElementById('page').contentWindow.document);
}
function createTree(c,o){
//get list of children
var children = o.childNodes;
//loop through them and display them
for (var i=0;i<children.length;i++){
if (typeof(children[i].tagName) !== 'undefined'){
//Create a tree node
var node = document.createElement('div');
if (children[i].childNodes.length > 0){
node.style.borderLeft = '1px dotted black';
node.style.marginLeft = '15px';
}
c.appendChild(node);
//Reference to the actual node
node.refNode = children[i];
//Add events
node.addEventListener('mouseover',selectNode,false);
//Display what type of tag it is
node.innerHTML += "<"+children[i].tagName.toLowerCase()+">";
//Add in its child nodes
createTree(node,children[i]);
//ending tag... CRASHES THE PROGRAM
node.innerHTML += "</"+children[i].tagName.toLowerCase()+">";
}
}
}
function selectNode(e){
document.getElementById('info').innerHTML = e.target.refNode;
}
</script>
</head>
<body>
<iframe id='page' src='some_page.html'></iframe>
<div id='info' style='border-bottom:1px solid red;margin-bottom:10px;'></div>
<div id='tree'></div>
</body>
</html>
我发现在添加子树节点之后添加 innerHTML 会带走子节点的 refNode 属性。所以,这就是问题所在。