【问题标题】:Automatically uncheck a checkbox when another checkbox is checked选中另一个复选框时自动取消选中一个复选框
【发布时间】:2017-02-20 10:34:17
【问题描述】:

我使用 XUL,我有两个 hbox,每个都有一个复选框:

<hbox id="hBox1">
   <label value="label1" style="width:15ex" />
   <spacer style="width:5px" />
   <checkbox id="checkBox1" style="width: 2ex" />
</hbox>

<hbox id="hBox2">
   <label value="label2" style="width:15ex" />
   <spacer style="width:5px" />
   <checkbox id="checkBox2" style="width: 2ex" />
</hbox>

我想要这种行为:两个复选框中只有一个可以被选中,即如果用户选中一个复选框而另一个被选中,那么第二个复选框必须自动取消选中

我试过这个:

<checkbox id="checkBox1" style="width: 2ex" onchange="if (this.checked) document.getElementById('checkBox2').checked = false" />

<checkbox id="checkBox2" style="width: 2ex" onchange="if (this.checked) document.getElementById('checkBox1').checked = false" />

但它不起作用

【问题讨论】:

    标签: checkbox xul


    【解决方案1】:

    当你应该使用concommand时,你正在使用onchange

    以下作品:

    <hbox id="hBox1">
       <label value="label1" style="width:15ex" />
       <spacer style="width:5px" />
       <checkbox id="checkBox1" style="width: 2ex" oncommand="if (this.checked) document.getElementById('checkBox2').checked = false" />
    </hbox>
    
    <hbox id="hBox2">
       <label value="label2" style="width:15ex" />
       <spacer style="width:5px" />
       <checkbox id="checkBox2" style="width: 2ex" oncommand="if (this.checked) document.getElementById('checkBox1').checked = false" />
    </hbox>
    

    但是,这将导致复选框标签实际上并未与复选框相关联(单击标签不会选中/取消选中复选框)并且通常会显示 &lt;checkbox&gt; label 的小图形工件。通常,左侧的标签将使用dir 属性实现:

    <hbox id="hBox1">
      <vbox id="vBox1">
       <checkbox id="checkBox1" dir="reverse" label="label1" style="width: 21ex" oncommand="if (this.checked) document.getElementById('checkBox2').checked = false" />
       <checkbox id="checkBox2" dir="reverse" label="label2" style="width: 21ex" oncommand="if (this.checked) document.getElementById('checkBox1').checked = false" />
      </vbox>
    </hbox>
    

    &lt;radio&gt; 按钮专门用于允许单个选择

    这通常在&lt;radiogroup&gt; 中使用&lt;radio&gt; 来实现。 &lt;radio&gt; 框在放置在 &lt;radiogroup&gt; 中时会自动具有此行为。它们的样式通常有点不同(圆形,而不是方形),但如果您愿意,可以使用 CSS 进行更改。但是,圆形样式旨在向用户提供它是单选按钮并具有此行为的信息。

    <hbox>
      <vbox>
        <radiogroup>
          <radio id="checkBox1" dir="reverse" label="label1" style="width: 21ex" />
          <radio id="checkBox2" dir="reverse" label="label2" style="width: 21ex" />
        </radiogroup>
      </vbox>
    </hbox>
    

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 2021-12-23
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2020-06-18
      相关资源
      最近更新 更多