javascript – Web Components,添加Shadow DOM事件?

我有三页.

第一个是索引页面,第二个页面是索引的组件.

第三,它是第二页的组件.

主要代码如下:
main.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>

子child.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规范中找到了我的名字.因此,我在这里回答.

点赞