[英]Polymer querySelector can't find custom polymer element in polymer element
[英]Can't find element inside template with querySelector - Polymer
當我嘗試從外部文件中查詢選擇模板標簽內的元素時,我未定義,經過一番搜索之后,我發現的唯一解決方案是“ shadowRoot”,但是當我嘗試使用它時,卻得到“ shadowRoot未定義”。
以下代碼對我來說很好( jsbin ):
<template is="auto-binding" id="tmpl">
<h1>Hello from {{foo}}</h1>
</template>
<script>
document.addEventListener('polymer-ready', function() {
var tmpl = document.querySelector('#tmpl');
tmpl.foo = 'my thing';
});
</script>
我添加了polymer-ready
事件,因為通常在等待所有元素准備就緒之后再嘗試使用它們是一種很好的做法。
編輯:OP想要知道如何在模板內查找元素
要在模板中定位元素,您需要使用模板的content
關鍵字querySelector
。 這是為了防止意外地選擇模板內的內容(例如,如果要查詢選擇器頁面上的所有p
標簽,則可能不希望在模板內尚未被標記的p
標簽)。
這是一個在template
( jsbin )內更改h2
的示例
<template is="auto-binding" id="tmpl">
<h1>Hello from {{foo}}</h1>
<h2>Another header</h2>
</template>
<script>
document.addEventListener('polymer-ready', function() {
var tmpl = document.querySelector('#tmpl');
tmpl.foo = 'my thing';
var h2 = tmpl.content.querySelector('h2');
h2.textContent = 'hello world';
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.