繁体   English   中英

Shadowroot:将 jquery 事件处理程序附加到 shadowRoot 下的多个元素

[英]Shadowroot : Attaching jquery event handlers to multiple elements under shadowRoot

所以我在我的应用程序的 shadowRoot 下使用了一个 jQuery 插件。 HTML如下

#shadow-root
<div id="container">
   <div class="display-item">Item 1</div>
   <div class="display-item">Item 2</div>
   <div class="display-item">Item 3</div>
   <div class="display-item">Item 4</div>
</div>

我想将事件侦听器附加到带有 class =“display-item”的 div,用于 mousedown、mousedown、focus 等事件。 我尝试了以下内容:

let root = document.getElementById(divID).shadowRoot;
$(root).on('mousedown', '#container div.display-item', function(event) {
//function 
});

但这不起作用。 我怎么能让这个工作?

编辑:

我也尝试过这种方法,比如 $('#container.display-item'),但它不会工作,因为它正在寻找文档下的那些元素,我相信它不会找到它们,因为它们在阴影下DOM,所以我必须使用根作为 pivot。是否有等效于 jquery 的“查找”方法,我可以在其中查询具有相同 class 的多个元素,使用影子根作为 pivot? 这样,我就可以将事件侦听器显式附加到各个元素。

在理想世界中 Web 组件应该关心“外部”世界,
最重要的是 Outside 不应该依赖于 Web Components inner world。

  • 这意味着组件应该负责附加侦听器。

  • 由于您可以控制组件的功能,因此不需要addEventListener (允许多个相同的侦听器)

 customElements.define("my-component", class extends HTMLElement { constructor() { super().attachShadow({mode: "open"}).innerHTML = `<div id="container"> <div class="display-item">Item 1</div> <div class="display-item">Item 2</div> <div class="display-item">Item 3</div> <div class="display-item">Item 4</div> </div>`; } listen() { this.shadowRoot.querySelectorAll('.display-item').forEach(div => { div.onclick = (evt) => { document.body.append(div.innerText); } }); this.listen = () => console.warn("ran attach listener once"); } })
 <my-component id=COMP></my-component> <script> window.onload=()=>{ document.querySelector("#COMP").listen(); } </script>

注意:IE9 是最后一个实现 JS queryselectors 的浏览器......在 2011 年

如果您仅将 jQuery 用于其$() ,那么在过去的 11 年中,您已经给客户带来了不必要的 80KB+ 下载负担。

如果你真的想接触内心世界

 document.querySelector("#COMP").shadowRoot.querySelectorAll('.display-item').forEach

可以解决问题,但是当两者之间有更多 shadowRoots 时就会中断。

在我的世界里,我不会告诉组件该做什么,
我让组件

      window.onload=()=>{
        document.dispatchEvent("LISTEN");
      }

如何集中注意力<textarea>&lt;i&gt;element that is located in shadowRoot in javascript or jquery?&lt;/div&gt;&lt;/i&gt;&lt;b&gt;位于 javascript 或 jquery 中 shadowRoot 的元素?&lt;/div&gt;&lt;/b&gt;</textarea><div id="text_translate"><p> DOM 结构如下所示:</p><p> <a href="https://i.stack.imgur.com/VXxr1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VXxr1.png" alt="在此处输入图像描述"></a></p><p> 我只想将focus()事件赋予这个 Textarea 元素,但它不起作用。</p><p> 我尝试的代码快照是:</p><pre> var email_text_box_pr = $('kat-textarea'); var email_text_box_sr = email_text_box_pr[0].shadowRoot; email_text_box = $(email_text_box_sr).find('textarea'); email_text_box.focus();</pre><p> 希望尽快得到任何人的帮助。</p><p> 问候</p></div>

[英]How to focus the <textarea> element that is located in shadowRoot in javascript or jquery?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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