我正在尝试在 HTML 页面中制作一个穷人的 Firebug。我创建了一个放置在目标页面某处的外部脚本。初始化为<body onload="monitor_init()">
。它还引入了一个样式表,以将部分不透明的表格与结果绝对定位。
所以它贯穿 window[]
中的所有内容(值) ,将其显示在一列中,以及 typeof(window[i])
在另一列中。我还希望有另一列显示变量或对象的名称。
function monitor_init()
{
var css = document.createElement("link");
css.setAttribute("href","jsmonitor.css");
css.setAttribute("rel","stylesheet");
css.setAttribute("type","text/css");
document.getElementsByTagName("head")[0].appendChild(css);
var temp = document.createElement("div");
temp.setAttribute("id","monitor_box");
var temp2 = document.createElement("table");
temp2.setAttribute("id","monitor_output");
temp.appendChild(temp2);
document.body.appendChild(temp);
monitor();
}
var monitor_speed = 100;
function monitor()
{
while(document.getElementById("monitor_output").childNodes.length > 0)
{
document.getElementById("monitor_output").removeChild(document.getElementById("monitor_output").lastChild);
}
for (i in window)
{
if (["function","undefined"].indexOf(typeof(window[i]))!=-1)
{
continue;
}
// This is where I tried to make a first column displaying the name, couldn't find anything that worked.
// Disregard the .name, that was just last-ditch stuff
//var temp = document.createElement("tr");
//var temp2 = document.createElement("td");
//temp2.appendChild(document.createTextNode(window[i].name));
//temp.appendChild(temp2);
var temp = document.createElement("tr");
var temp2 = document.createElement("td");
temp2.appendChild(document.createTextNode(typeof(window[i])));
temp.appendChild(temp2);
var temp2 = document.createElement("td");
temp2.appendChild(document.createTextNode(window[i]));
temp.appendChild(temp2);
document.getElementById("monitor_output").appendChild(temp);
}
setTimeout("monitor()",monitor_speed);
}
通过使用 typeof 我能够跳过显示函数的值和一些未定义的东西。我希望如果我能够访问该名称,我还可以跳过历史记录、位置以及其他非 JavaScript 数字、字符串、数组对象等内容,即我在其他脚本中创建的全局变量在页面上。
最佳答案
您并没有真正提出具体问题,但我认为您想说“如何获取窗口
的每个属性的名称?”
在现有代码中,您使用 for-in 循环来遍历各种属性。我认为您需要知道的是您的索引变量将保存(当前)属性的名称:
for (i in window) {
alert("Property name: " + i);
alert("Property value: " + window[i]);
}
关于javascript - 在 window[]、html/javascript 中显示变量(或所有内容)的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6701280/