【问题标题】:How can I get the JS code of an existing HTML element?如何获取现有 HTML 元素的 JS 代码?
【发布时间】:2014-05-06 18:49:56
【问题描述】:

我想知道是否有任何方法可以使用任何现有方法获取现有 HTML 元素的 JS 代码。我正在尝试打印任何 DOM 元素的代码生成器,因此当用户单击网页的任何 HTML 元素时,将显示一条消息,其中包含在 Javascript 中创建该元素的源代码。

例如,我创建了一个 Div:

var div = document.createElement("div");
div.style.border = "1px dotted red";
div.onmouseover=function(){div.style.color = "red"};
div.innerHTML = "I'm the div";

然后我试图获取源代码,但是:

document.body.appendChild(div.innerHTML);

此选项仅写入文本内容:“我是 div”。所以我尝试了:

document.body.appendChild(div.outerHTML);

但它编写的 HTML 代码没有 onmouseover 功能:“我是 div”

我真正需要的是展示这段代码(或类似的东西):

var div = document.createElement("div");
div.style.border = "1px dotted red";
div.onmouseover=function(){div.style.color = "red"};
div.innerHTML = "I'm the div";

http://jsfiddle.net/x2zJs/

您知道我可以从哪里开始阅读吗? 非常感谢,

【问题讨论】:

  • HTML 文件中的 HTML 元素呢?
  • 所以你想生成 JavaScript 代码来生成那个元素?
  • 是的 Chevi,我想生成任何选定的 dom 元素的代码
  • 您无法获取用于制作元素的代码。您可以制作一些代码来创建类似于您单击的元素的代码,这样可以吗?
  • @gal007 我希望我的回答能帮助您获取事件的代码。您的插件还有其他问题需要解决吗?

标签: javascript dom firefox-addon


【解决方案1】:

外部HTML

outerHTML 是一个不错的选择,但有几个限制:

  1. 今天(2014)you can't get attached listeners natively
  2. outerHTML 使用 html node serialization,它使用使用 xml attributes serialization algorithm

换句话说,IDL 属性被忽略,只有内容属性被序列化。

IDL 属性的事件被编码为

div.onmouseover=function(){div.style.color = "red"};
div.addEventListener("mouseover",function() {div.style.backgroundColor="blue";});

查看更多关于events

而按内容属性的事件被编码为

div.setAttribute("onmouseover","this.style.color='red'");

使用 content 属性,outerHTML 看起来像这样:

<div onmouseover="this.style.color='red'" style="border: 1px dotted red;">
  I'm the div
</div>

your updated fiddle

长话短说,编写处理程序有两种方法:

var setColor = function(e) { e.target.style.color = "red"; }
div.onmouseover = setColor; // IDL, not seen by outerHTML
div.setAttribute("onmouseover","setColor(event)"); // content, seen by outerHTML

事件监听器列表

如果您想以某种方式检索 IDL 事件,好的建议 eventListenerList 属性已从 DOM3 规范提案中删除(请参阅 here)。

如果你想编写一个 firefox 插件(类似于代码检查器),扩展 Element.prototype 就可以解决问题(正如我所测试的,它适用于 Firefox、Chrome 和 Opera,它不适用于 IE7):

(function() {
  Element.prototype.eventListenerList = {};
  Element.prototype._addEventListener = Element.prototype.addEventListener;
  Element.prototype.addEventListener = function(a,b,c) {
    this._addEventListener(a,b,c);
    if(!this.eventListenerList[a]) this.eventListenerList[a] = [];
    this.eventListenerList[a].push(b);
  };
})();

确切地说,您还应该覆盖 Element.prototype.removeEventListener 以从自定义 EventListenerList 中删除事件。

现在您可以像往常一样通过addEventListener 添加事件:

function handlerA() { alert('a'); }
function handlerB() { alert('b'); }
function handlerC() { alert('c'); }

// attach handlers
div.onclick = handlerC;
div.addEventListener("click",handlerA);
div.addEventListener("click",handlerB);

...并显示侦听器的代码。我将为onclick 事件执行此操作,在您的代码中,您应该遍历每个可能的事件。不要忘记最终的 onclick 监听器(您不能覆盖 Element.prototype.onclick,因为它是不可配置的属性):

var clickListeners = "";
if(div.eventListenerList.click)
div.eventListenerList.click.forEach(function(f) {
  clickListeners+= f.toString();
});
if(div.onclick) clickListeners+= div.onclick.toString();
alert(clickListeners);

查看并测试the fiddle。根据您的插件将这些部分组合在一起。

【讨论】:

    【解决方案2】:

    没有任何内置功能可以满足您的需求,请尝试使用“土豚书签”,它有一个不错的 js 生成命令。 http://karmatics.com/aardvark/bookmarklet.html

    【讨论】:

      【解决方案3】:

      好吧,你可以用一个函数来包装 div 元素的创建,然后解析并打印该函数的内容。

      以下是一个工作示例(在 Chrome、Firefox 和 Safari 中测试):
      也在这里http://jsfiddle.net/smnh/x2zJs/2/

      function createDiv() {
          var div = document.createElement("div");
          div.style.border = "1px dotted red";
          div.onmouseover = function() {div.style.color = "red"};
          div.innerHTML = "I'm the div";
          div.creationString = getFunctionContnet(createDiv); // noprint
          return div; // noprint
      }
      
      function getFunctionContnet(func) {
          var regExp = /function[^(]*\([^)]*\)[^{]*{(?:\s*\n)?(\s*)([\s\S]*)(?:\n\s*)}/,
              match,
              indention, indentionRE,
              noprintRE = /\/\/.*noprint.*/,
              content = null,
              lines, i;
      
          match = regExp.exec(func.toString());
      
          if (match !== null) {
              indention = match[1];
              content = match[2];
      
              lines = content.split("\n");
      
              // if first line of the function is indented,
              // remove that indention from all function lines.
              if (typeof indention !== "undefined") {
                  indentionRE = new RegExp("^" + indention);
                  for (i = 0; i < lines.length; i++) {
                      if (indentionRE.test(lines[i])) {
                          lines[i] = lines[i].substr(indention.length);
                      }
                  }
              }
      
              // don't print lines with "// noprint"
              for (i = lines.length - 1; i >= 0; i--) {
                  if (noprintRE.test(lines[i])) {
                      lines.splice(i, 1);
                  }
              }
      
              content = lines.join("\n");
          }
      
          return content;
      }
      

      如果您在此处创建 div 并记录 creationString,您将获得函数的文本。

      div = createDiv();
      console.log(div.creationString);
      

      【讨论】:

        【解决方案4】:

        如果您可以控制元素的创建,则可以确保每个元素都是在其自己的单独函数中创建的。然后一个简单的函数就可以得到函数体。

        function createElement1() {
            var div = document.createElement("div");
            div.style.border = "1px dotted red";
            div.onmouseover=function(){div.style.color = "red"};
            div.innerHTML = "I'm the div";
        }
        
        function getFunctionBody(func) {
            var functionText = func.toString();
            return functionText.slice(functionText.indexOf("{") + 1, functionText.lastIndexOf("}"));
        }
        

        这是一个工作示例。 http://jsfiddle.net/C5b7n/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-08
          • 1970-01-01
          • 1970-01-01
          • 2016-07-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多