2017-02-26 34 views
2

我想獲得HTML元素的所有屬性,樣式,事件和方法的列表。瀏覽器中是否有反射API?瀏覽器中的JavaScript是否有反射機制?

我正在尋找這樣的事情:

var button = new HTMLButtonElement(); 
var className = document.getQualifiedClassName(button); // "HTMLButtonElement" 
var definition = document.getDefinition(className); // HTMLButtonElement reference 
var instance = document.getInstance(definition); // instance of HTMLButtonElement 
var properties = document.getProperties(button); // properties of HTMLButtonElement 
var methods = document.getMethods(button); // methods of HTMLButtonElement 
var styles = document.getStyles(button); // styles applicable to HTMLButtonElement 
var events = document.getEvents(button); // events on HTMLButtonElement 
var inheritance = document.getInheritance(button); // HTMLButtonElement > HTMLElement 

編輯:
這是基於ActionScript3的調用得到什麼我在尋找:

var objectInformation = document.describeType(button) // metadata 

這可能讓它更清楚我想要在JavaScript中做什麼。

背景
假設我想將代碼完整添加到HTML代碼編輯器。當用戶將他們的光標放在div元素旁邊並啓動代碼完成時,我想向他們展示代碼完成時彈出的所有事件和屬性和樣式。當他們在JavaScript中輸入時,我想自動完成所有可用的方法。當他們開始輸入樣式對象時,我想提供一個樣式列表。

如果我得到一個對象或標籤名稱,我需要能夠顯示代碼完成的所有元數據。在很多語言中都有API來執行此操作。

回答

2

JS中沒有什麼像AS3's describeType。你一次要求很多事情,其中​​一些你可以在JS中獲得,其中一些你不能(其中一些甚至可能在JS中沒有意義,因爲它非常動態。)

可以當然可以使用Object.getOwnPropertyDescriptors()Object.getPrototypeOf()獲取對象及其層次結構的屬性和方法。

function describeType(object) { 
    const prototype = Object.getPrototypeOf(object); 
    console.log("Hello, I am a", prototype.constructor.name); 
    console.log("My properties are", Object.getOwnPropertyDescriptors(object)); 
    console.log("My prototype proterties are", Object.getOwnPropertyDescriptors(prototype)); 
    const superPrototype = Object.getPrototypeOf(prototype); 
    if (superPrototype) { 
     console.log("My super class is", superPrototype.constructor.name); 
     // etc 
    } 
} 

Example on jsfiddle

1
var button = document.createElement('button') 

for(key in button){ 
//do anything here 
} 

你可以這樣做,我認爲。

2

你必須定義每件事情的含義。

var className = document.getQualifiedClassName(button);

這是什麼意思?您可以使用classList

var definition = document.getDefinition(className);

這是什麼意思?你的意思是CSS規則?你必須走CSS對象模型才能找到它。

var instance = document.getInstance(definition);

這是什麼意思?您可以使用querySelectorAll

var properties = document.getProperties(button);

如果您確實是指屬性,您可以簡單地遍歷該按鈕的屬性作爲對象。

var methods = document.getMethods(button);

大多數有趣的方法將在原型上,如HTMLElement,你必須在那裏尋找它們。許多或大多數將是不可枚舉的,並且可能很難追查到。

var styles = document.getStyles(button);

你是什麼意思? button.style

var events = document.getEvents(button);

有沒有辦法得到這些。

var inheritance = document.getInheritance(button);

這是什麼意思?

您還可以獲得屬性,這是不同於屬性:

VAR屬性= button.attributes;

相關問題