如何在Polymer自定义元素中使用getElementById?
这是我的元素:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../styles/shared-styles.html">
<dom-module id="bb-calendar">
<template>
<style is="custom-style" include="shared-styles"></style>
<div class="card">
<paper-toolbar>
<div title>Calendar</div>
</paper-toolbar>
<div id="hideme">
<div>this should be hidden</div>
</div>
</div>
</template>
<script>
Polymer({
is: 'bb-calendar',
ready: function() {
document.getElementById("hideme").style.display = 'none';
}
});
</script>
</dom-module>
当我运行代码时,我收到此错误消息: Uncaught TypeError: Cannot read property 'style' of null
显然我做错了但我不知道是什么。
我用了
ready: function() {
this.$.hideme.style.display = 'none';
}
当元素在里面时 <template dom-if...>
要么 <template dom-repeat...>
ready: function() {
this.$$('#hideme').style.display = 'none';
}
最后,我将使用类绑定并将类绑定到元素并更新属性以反映该更改并使用CSS来设置 style.display
<template>
<style>
.hidden { display:none; }
</style>
...
<div class$="{{hiddenClass}}">
<div>this should be hidden</div>
</div>
Polymer({
is: 'bb-calendar',
properties: {
hiddenClass: String,
},
ready: function() {
this.hiddenClass = 'hidden';
}
});
我用了
ready: function() {
this.$.hideme.style.display = 'none';
}
当元素在里面时 <template dom-if...>
要么 <template dom-repeat...>
ready: function() {
this.$$('#hideme').style.display = 'none';
}
最后,我将使用类绑定并将类绑定到元素并更新属性以反映该更改并使用CSS来设置 style.display
<template>
<style>
.hidden { display:none; }
</style>
...
<div class$="{{hiddenClass}}">
<div>this should be hidden</div>
</div>
Polymer({
is: 'bb-calendar',
properties: {
hiddenClass: String,
},
ready: function() {
this.hiddenClass = 'hidden';
}
});
您的问题实际上是在触发就绪回调时您的元素未附加到文档DOM。要简单地显示/隐藏元素,您可以使用隐藏属性,如下所示: <div hidden$="{{!shouldShow}}">