[英]How to inherit all event handlers from a custom object in Javascript
[英]How to select all custom element that inherit from a specific javascript class
現在,我想嘗試使用webComponent 。 我創建了一個組件,該組件應該代表我所有其他可翻譯組件的父類。 它現在可以按我的意願工作,但是我想有一種方法來選擇從該父類繼承的當前文檔的所有元素。 就像是:
document.getElementsByTagName('lsp-motherComposant');
不起作用。
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>WebComponentTest</title>
<!-- motherComponent -->
<link rel="import" href="components/lsp-translatable/lsp-
translatable.html" />
<!-- child Component -->
<link rel="import" href="components/lsp-button/lsp-button.html" />
</head>
<body>
<select id="lang">
<option value="fr" selected>fr</option>
<option value="en">en</option>
<option value="zh">zh</option>
</select>
<lsp-button i18n="events" width="33%" gradient color1="0,0,0,0"
color2="128,0,128,1" direction="left"></lsp-button>
<script type="text/javascript">
window.onload = function(){
document.getElementsByTagName('lsp-translatable');
// => empty node list
};
</script>
</body>
</html>
LSP-translatable.js:
class LspTranslatable extends HTMLElement {//some stuff}
customElements.define('lsp-translatable', LspTranslatable);
LSP-button.js:
class LspButton extends LspTranslatable {//some stuff}
customElements.define('lsp-button', LspButton);
您是否嘗試過document.querySelectorAll
?
const components = document.querySelectorAll('lsp-button'); console.log(components); console.log(Array.from(components));
lsp-button { position: static; display: block; border: 1px solid #6F6; height: 1rem; width: 1rem; }
<lsp-button id="button-0"></lsp-button> <lsp-button id="button-1"></lsp-button> <lsp-button id="button-2"></lsp-button> <lsp-button id="button-3"></lsp-button> <lsp-button id="button-4"></lsp-button> <lsp-button id="button-5"></lsp-button> <lsp-button id="button-6"></lsp-button> <lsp-button id="button-7"></lsp-button> <lsp-button id="button-8"></lsp-button> <lsp-button id="button-9"></lsp-button>
getElementsByTagName
對我來說很好
如果要查找特定屬性,例如document.querySelectorAll('img[title]')
(所有具有title屬性的圖像document.querySelectorAll('img[title]')
則可以使用document.querySelectorAll
console.log( Array.from(document.getElementsByTagName('randomComponent')) );
randomComponent { position: static; display: block; border: 1px solid #6F6; height: 1rem; width: 1rem; }
<randomComponent id="1"></randomComponent> <randomComponent id="2"></randomComponent>
為了確保您使用querySelector()
屬性選擇的所有自定義元素確實是從特定的Javascript類繼承的,您應該使用instanceof
每個元素進行測試。
window.onload = function() {
const els = document.querySelectorAll( '[i18n]' )
const translatableNodes = Array.from(els).filter( el => el instanceof LspTranslatable )
}
這不會對您的生產代碼有所幫助,但這是您要尋找的開發版本。
Chrome DevTools具有開發人員命令queryObjects ,該命令將返回類的所有實例。 在Chrome DevTools中,您可以運行以下命令:
queryObjects(LspTranslatable);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.