【问题标题】:Using jQuery with shadow dom使用带有阴影 dom 的 jQuery
【发布时间】:2016-11-04 10:40:20
【问题描述】:

在这里,我创建了带有 shadow dom 的元素。

/* some preparing code */
this.createShadowRoot();  // creates shadow root, this refers to element

稍后在代码中,我将访问我创建的影子 dom。这些工作:

this.shadowRoot.getElementById("...")
this.shadowRoot.querySelector("...")

但事实并非如此:

$("...", this.shadowRoot)

这是为什么呢?作为临时解决方案t他目前的作品

$("...", this.shadowRoot.children)

有没有更好/更优雅的方式来使用 jQuery 处理影子根?

请注意,我使用的 jQuery 版本是 2.1.1,我只处理 Chrome。


编辑:显然this.shadowRoot.children 在顶层查找节点时不起作用。

【问题讨论】:

    标签: javascript jquery html shadow-dom


    【解决方案1】:

    这可能是 jQuery 2.1.1 的问题。

    在 jsfiddle 中使用 jQuery 2.1.3 似乎可以解决这个问题:

    https://jsfiddle.net/bnh74s87/

    document.addEventListener("DOMContentLoaded",function(){
      var div=document.getElementById("dTest");
      var shadow=div.createShadowRoot();
      shadow.innerHTML='<p>Hi!</p>';
      document.body.appendChild(document.createTextNode(shadow.childNodes.length));
      console.log(shadow.querySelectorAll("p"));
      console.log($("p",shadow));
      $("p",shadow).html("Hello!");
    },false);
    <script src="https://code.jquery.com/jquery-2.1.3.js"></script>
    <div id="dTest"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      相关资源
      最近更新 更多