简体   繁体   English

如果选中,则从纸张复选框获取价值

[英]Get value from paper-checkbox if checked

A similar question has been asked and I am trying to do the same with paper-checkbox in Polymer 1.1 有人问过类似的问题 ,我正在尝试使用Polymer 1.1中的paper-checkbox做同样的事情

Here is my full setup: 这是我的完整设置:

<dom-module id="my-app">
 <template>
  <firebase-collection
   location="htt://www.abc.com/users"
   order-by-child="formatOrder"
   data="{{users}}">
  </firebase-collection>
  <template is="dom-repeat" items="[[users]]" as="user">
   <paper-checkbox id="user-checked" value="{{user.name}}" on-tap="userRequest">click</paper-checkbox>
  </template>
 </template>
 <script>
  Polymer({
   is: "my-app",

   userRequest: function() {
    var cbs = document.querySelectorAll('#user-checked');
    for(var i = 0; i < cbs.length; i++) {
     cbs[i].addEventListener('change', function() {
      if(this.checked) {
       console.log(this.value);
      }
     });
    }
   },
  });
 </script>
</dom-module>

So basically I want when the checkbox is checked, it shows their name. 因此,基本上我想在选中该复选框时显示其名称。 If I decided to add another checkbox for their age, it does the same. 如果我决定为他们的年龄添加另一个复选框,它也会这样做。 But the code above runs the code twice, when checked or unchecked, even three times. 但是,上面的代码在选中或未选中时两次运行该代码,甚至运行三次。 How to get it to execute once when checked and not to execute when unchecked? 如何使它在选中时执行一次而在未选中时不执行?

Every time someone taps the checkbox you add an event listener for the change event in your userRequest function. 每次有人点击复选框时,都会在userRequest函数中为change事件添加一个事件侦听器。 Thus, the more often the user taps the checkbox, the more event listeners you will have for the same event. 因此,用户点击复选框的次数越多,针对同一事件的事件侦听器就会越多。 They will all get called each time the event fires. 每当事件触发时,他们都会被呼叫。 But actually you only need one and you can add in the markup directly . 但是实际上您只需要一个即可直接添加标记。

<paper-checkbox on-change="checkboxChanged">click</paper-checkbox>

Then in your event handler you can access the checkbox value via event.target.value 然后,在事件处理程序中,您可以通过event.target.value访问复选框值

checkboxChanged : function(event){
    if(event.target.checked) {
        console.log(event.target.value);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM