这里我用shadow dom创建了元素。
/* some preparing code */
this.createShadowRoot(); // creates shadow root, this refers to element
稍后在代码中我将访问我创建的影子 dom。这些工作:
this.shadowRoot.getElementById("...")
this.shadowRoot.querySelector("...")
但是这不会:
$("...", this.shadowRoot)
这是为什么呢?作为临时解决方案,它目前有效:
$("...", this.shadowRoot.children)
有没有更好/更优雅的方法来使用 jQuery 处理影子根?
请注意,我使用的 jQuery 版本是 2.1.1,并且我只处理 Chrome。
编辑:显然 this.shadowRoot.children
在查找顶层节点时不起作用。
最佳答案
这可能是 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>
关于javascript - 将 jQuery 与 Shadow dom 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38155218/