[英]document.querySelector() returns null
我正在创造一种聚合物元素。 我已经制作了模板,现在正在编写脚本。 由于某种原因,document.querySelector为类和id选择器返回null。 不确定这是否与聚合物不起作用(没有理由不应该)或者我没有输入某些东西或者其他什么是错误的。
事件card.html
<link rel="import" href="../components/polymer/polymer.html">
<link rel="import" href="event-card-description.html">
<polymer-element name="event-card" attributes="header image description">
<template>
<style>
.card-header {
display: block;
position: static;
font-size: 1.2rem;
font-weight: 300;
width: 300px;
height: 300px;
border-radius: 50%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
overflow: hidden;
}
event-card-description {
margin: 0;
position: relative;
top: 225px;
}
</style>
<div
style="background: url(../images/{{image}}.jpg) no-repeat; background-size: cover"
class="card-header" layout horizontal center
on-mouseover='{{onHovered}}'
on-mouseout='{{onUnhovered}}'>
<event-card-description
id="description"
header={{header}}
description={{description}}>
</event-card-description>
</div>
</template>
<script>
Polymer('event-card', {
onHovered: function() {
var elem = document.querySelector("#description");
console.log(elem);
}
});
</script>
</polymer-element>
<event-card-description id="description">
在你元素的影子dom中。 document.querySelector("#description")
正在主文档中查找id#description
为#description的节点。 由于阴影dom边界隐藏了节点,因此预计找不到该节点。 尝试:
this.shadowRoot.querySelector("#description");
但是,Polymer有一个很棒的功能,其中具有id的静态元素映射this.$.<id>
。 您可以使用this.$.description
来获取该元素。
对于属性中的多个值,使用~
符号, 例如
var elem = document.querySelector("[attributes~=description]");
或者如果您只想将其用于元素polymer-element
:
var elem = document.querySelector("polymer-element[attributes~=description]");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.