【问题标题】:Checkbox's checked property binding - PolymerCheckbox 的选中属性绑定 - Polymer
【发布时间】:2016-08-27 20:16:53
【问题描述】:

我正在尝试将Polymer 属性绑定到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>

我做错了什么?提前致谢。

【问题讨论】:

    标签: javascript html checkbox polymer


    【解决方案1】:

    几个问题:

    1. 您的模板缺少 is="dom=if",因此它实际上在您的代码中没有任何作用。

    2. 即使应用了dom-ifif 属性也会设置为checked,它没有初始值。仅当绑定属性具有非undefined 值时才评估绑定,并且由于从未设置checked,因此您的模板不会标记任何内容(即,您不会看到“检查”或“取消检查” )。

      properties: {
        checked: {
          type: Boolean,
          value: false  // initial value required for binding
        }
      }
      
    3. 您的模板文本向后看。 if="{{checked}}" 的文本内容是“取消选中”,而if="{{!checked}}" 是“选中”。也许这些是用户说明而不是复选框状态。

    4. 本机input 不会为其checked 属性发出更改事件,因此绑定不会更新您的checked 属性。相反,您可以更新您的点击处理程序以显式设置您的checked 属性以匹配inputchecked 的值。

      _checkBoxClicked: function(e) { this.checked = this.$.input.checked; }
      
    5. 您的labelinput 没有关联,因此单击它不会更改checkbox 的状态。你可以通过使用labelfor来解决这个问题:

      <label for="foo">...</label>
      <input id="foo">
      

      或者通过使input 成为label 的孩子:

      <label>
        <input>
      </label>
      

    codepen

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 2010-12-02
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2018-07-13
      • 2016-04-26
      相关资源
      最近更新 更多