【问题标题】:How to know if a checkbox or radio button is checked in Dart?如何知道 Dart 中是否选中了复选框或单选按钮?
【发布时间】:2012-10-22 07:57:44
【问题描述】:

我有一个复选框和一个单选按钮组,我想知道是否选中了复选框以及选择了哪个单选按钮。

我如何在飞镖中做到这一点?

【问题讨论】:

  • 可以添加html代码吗?

标签: checkbox radio-button dart checked


【解决方案1】:

假设我们有这样的 HTML:

    <form >
      <input type="radio" name="gender" id="gender_male" value="male">Male<br>
      <input type="radio" name="gender" id="gender_female" value="female">Female
    </form>

    <form>
      <input type="checkbox" id="baconLover">I like bacon<br>
    </form>

获取它们的值的 Dart 代码如下所示,我还添加了一个事件来知道何时单击了复选框。

import 'dart:html';

void main() {

  // Adds a click event when the checkbox is clicked
  query("#baconLover").on.click.add((MouseEvent evt) {
    InputElement baconCheckbox = evt.target;

    if (baconCheckbox.checked) {
      print("The user likes bacon");
    } else {
      print("The user does not like bacon");
    }

  });

  // Adds a click event for each radio button in the group with name "gender"
  queryAll('[name="gender"]').forEach((InputElement radioButton) {
    radioButton.onclick.listen((e) {
      InputElement clicked = e.target;
      print("The user is ${clicked.value}");
    });
  });

}

【讨论】:

  • 如果用户使用 tab 键导航到控件,然后使用空格键选择它,这会中断吗? (编辑,令人惊讶的是:不,它仍然有效)
  • @Günter 我不得不将 radioButton.on.click 更改为 radiobutton.onClick 但 API 中似乎没有 add() 方法。也应该将InputElement 更改为RadioButtonInputElement
【解决方案2】:

我为单选按钮找到了this solution,其中通过“html”捕获事件...我已将此解决方案用于我的项目中。

my_example.html

<polymer-element name="my-example">
  <template>
    <div on-change="{{updateRadios}}">
      Your favorite color is:
      <div>
        <label for="red">Red <input name="color" type="radio" id="red" value="red"></label>
      </div>
      <div>
        <label for="green">Green <input name="color" type="radio" id="green" value="green"></label>
      </div>
      <div>
        <label for="blue">Blue <input name="color" type="radio" id="blue" value="blue"></label>
      </div>
    </div>
    <div>
      You selected {{favoriteColor}}
    </div>
  </template>
  <script type="application/dart" src="my_example.dart"></script>
</polymer-element>

my_example.dart

import 'package:polymer/polymer.dart';
import 'dart:html';

@CustomTag('my-example')
class MyExample extends PolymerElement {
  @observable String favoriteColor = '';

  MyExample.created() : super.created();

  void updateRadios(Event e, var detail, Node target) {
    favoriteColor = (e.target as InputElement).value;
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2013-01-23
    • 2015-11-30
    • 2013-02-07
    • 2017-09-14
    相关资源
    最近更新 更多