使用querySelector - Polymer找不到模板内的元素 [英] Can't find element inside template with querySelector - Polymer
问题描述
当我尝试从外部文件中选择一个模板标签中的一个元素时,我得不明确,经过一点搜索,我发现唯一的解决方案是shadowRoot,但是当我尝试使用它时,我得到'shadowRoot不是定义'。
When I try to querySelector an element inside a template tag from external file I get undefined, after a little bit of searching the only solution I found was the 'shadowRoot' but when I tried to use it I got 'shadowRoot is not defined'.
推荐答案
以下代码对我有用( jsbin ):
The following code works fine for me (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>
我添加了聚合物就绪
事件,因为一般来说,等待所有元素准备好,然后再尝试一下,这是一个很好的做法。
I added the polymer-ready
event since it's generally a good practice to wait for all of your elements to be ready before trying to play around with them.
编辑:OP想知道如何在模板中找到一个元素
要在模板中定位元素,您需要 querySelector
使用模板的内容
关键字。这是为了防止意外地选择模板中的内容(例如,如果您要查询选择器所有 p
标签在页面上,您可能不需要一个 p
标签里面的一个模板,还没有被打印出来)。
To locate an element inside of a template you'll need to querySelector
using the template's content
keyword. This is to prevent accidentally selecting things inside of templates (for example, if you were to query selector all p
tags on the page, you might not want a p
tag inside of a template that hasn't been stamped out yet).
这是一个例子,改变一个 h2
模板
( jsbin )
Here's an example which changes an h2
inside the template
(jsbin)
<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>
这篇关于使用querySelector - Polymer找不到模板内的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!