我有三个页面。 第一个是索引页面,第二个页面是索引组件。 第三,它是第二页的组件。
主要代码如下: 主.html:
<link class="abc" rel="import" tag="linkHtml" href="child.html />
<say-hi name="aaaa"></say-hi>
<shadow-element>
<span>(I'm in the light span dom)</span>
<div>(I'm in the light div dom)</div>
</shadow-element>
Child.html:
<template id="t1">
....
<my-search value="Search"></my-search>
<content select="div"></content>
</template>
子子.html:
<template id="t2">
Search:<input type="text" id="txt1" />
<input type="button" id="btn1" value="Search" />
<template id="t2">
<script>
//mainDoc
var importDoc_sub = document.currentScript.ownerDocument;
var proto3 = Object.create(HTMLElement.prototype);
proto3.createdCallback = function(){
var template = importDoc_sub.querySelector("#t2");
var clone = document.importNode(template.content,true);
var root = this.createShadowRoot();
root.appendChild(clone);
}
document.registerElement("my-search",{prototype:proto3});
//it can not register click event for btn1 button
document.addEventListener("click",function(e){
console.log(e.target.id);
},false);
//how to add event for the btn1
//todo
问题是如何在Shadow DOM中为btn1添加Event。
最佳答案
您可以通过ShadowRoot.querySelector查询元素。因此,答案应该是:
root.querySelector('#btn1').addEventListener("click", ....);
注意: 我从发帖人那里收到了关于这个问题的直接电子邮件,因为发帖人在 Shadow DOM 规范上找到了我的名字。因此,我在这里回答。
关于javascript - Web 组件,添加 Shadow DOM 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36347067/