我正在尝试将 Polymer
属性绑定(bind)到 CheckBox
的选中属性。然而,属性的观察者永远不会被解雇,此外,标签也永远不会显示任何文本。
但是,每次单击 CheckBox
时,我都能执行一个函数。
这是我的代码:
<link rel="import" href="../../components/polymer/polymer.html">
<dom-module id="check-box-example">
<template>
<div>
<label>
<template if="{{checked}}">Uncheck</template>
<template if="{{!checked}}">Check</template>
</label><br>
<input type="checkbox" checked="{{checked}}" on-click="_checkBoxClicked">Check Box
</div>
</template>
<script>
Polymer({
is: 'check-box-example',
properties:{
checked: {
type: Boolean,
observer: '_checkedChanged'
}
},
_checkBoxClicked: function() {
console.log("The Check Box was clicked.");
},
_checkedChanged: function(newValue, oldValue) {
console.log("New Checkbox value: " + newValue);
},
});
</script>
</dom-module>
我做错了什么?提前致谢。
最佳答案
几个问题:
您的模板缺少
is="dom=if"
,因此它在您的代码中实际上什么都不做。即使应用了
dom-if
,if
属性也会设置为checked
,它没有初始值。只有当绑定(bind)属性具有非undefined
值时才会评估绑定(bind),并且由于从未设置checked
,您的模板不会标记任何内容(即,您不会看不到“选中”或“取消选中”)。properties: { checked: { type: Boolean, value: false // initial value required for binding } }
您的模板文本向后看。
if="{{checked}}"
的文本内容是"Uncheck",而if="{{!checked}}"
是"Check"。也许这些是用户说明而不是复选框状态。原生
input
不会为其checked
属性发出更改事件,因此绑定(bind)不会更新您的checked
属性(property)。相反,您可以更新您的点击处理程序以明确设置您的checked
属性以匹配input
的checked
的值。_checkBoxClicked: function(e) { this.checked = this.$.input.checked; }
您的
label
与input
没有关联,因此单击它不会更改checkbox
的状态。您可以使用label
的for
来解决这个问题:<label for="foo">...</label> <input id="foo">
或者通过使
input
成为label
的子元素:<label> <input> </label>
关于javascript - Checkbox 的 checked 属性绑定(bind) - Polymer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39185367/