javascript - 在 window[]、html/javascript 中显示变量(或所有内容)的名称

标签 javascript html dom variables window

我正在尝试在 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/

相关文章:

Python Mechanize 无法识别表单

html - 在较长的 P 或 DIV 中垂直展开 jQuery 按钮

javascript - jquery:仅保留单个选定的div

Javascript 图像 src 没有改变

JavaScript DOM 编码 - 'undefined' 错误

javascript - HTML5 自定义密码验证

javascript - Handlebars - 基于模板中数组键的计算

html - CSS Hover 适用于一个元素,但不适用于其他元素

javascript - 不明确的 multi_select 过滤器 - AND 和 OR 条件 - javascript

javascript - jQuery fn 等效项