简体   繁体   中英

Web Components, add Shadow DOM Event?

I have three pages. First one is the index page, second page is the component for index. Third it the component for the second page.

The Main Code is below: 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>

Sub-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

The question is how to add Event for btn1 in Shadow DOM.

You can query the element by ShadowRoot.querySelector. Thus, the answer should be:

root.querySelector('#btn1').addEventListener("click", ....);

Note: I received the direct email about this question from the poster because the poster found my name on the Shadow DOM spec. Thus, I am answering here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM