我正在尝试学习 Polymer 2.0,但一直无法解决从不同的 Shadow Dom 获取元素的问题。这在 Polymer 1 中有效,但在 Polymer 2.0 中不再有效。正确的写法是什么?它只是告诉我 targetText = Null
。
感谢您的帮助!
这是一个 MWE: 聚合物 WC 1:
<dom-module id="sc-navdrawer">
<template>
<style is="custom-style">
p {
font-weight: bold;
}
.changed {
color: red;
}
</style>
<p>Some text in normal p tag</p>
<div id="test" class="htmltextcontent" inner-h-t-m-l="{{inputText}}"></div>
</template>
<script>
Polymer({
is: 'sc-navdrawer',
properties: {
inputText: {
type: String,
value: "<p>Some innerhtml text in p tags</p>"
}
}
});
</script>
</dom-module>
聚合物 WC 2:
<dom-module id="sc-testpage">
<template>
<button onclick="{{changeColor}}">Click here to change color</button>
</template>
<script>
Polymer({
is: 'sc-testpage',
changeColor: function() {
var targetText = document.getElementById("test");
console.log(targetText);
targetText.classList.add("changed");
}
});
</script>
</dom-module>
最佳答案
我首先看到的是您使用了 document.getElementById("test");
,如果您说这有效,那么您已经使用了 Shady Dom。
Polymer 2 强制您使用 Shadow Dom,因此此命令应替换为 Polymer.dom(this.root).querySelector("#test")
。因为 Shadow Dom 封装了您的组件,所以您无法使用 document
对象访问其内容
但这不应该解决你的问题。这种封装意味着您无法访问 WebComponent 的内容,因此您无法从另一个组件访问具有 id:xyz 的元素。查看这些链接,它们将向您解释 shadowDom 的工作原理:
1. https://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/
2. https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM
3. https://glazkov.com/2011/01/14/what-the-heck-is-shadow-dom/
关于javascript - 不同ShadowDom中的Polymer 2.0 getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45463115/