【问题标题】:jQuery to only show labels of checked checkboxes and hide the unchecked onesjQuery 仅显示选中复选框的标签并隐藏未选中的复选框
【发布时间】:2013-01-20 00:45:01
【问题描述】:

我有这个设置:

<style>.selectit{display:none;}</style>
<div id="foo">
<label class="selectit">
<input type="checkbox" name="one" id="one" checked>
One
</label>
<label class="selectit">
<input type="checkbox" name="two" id="two">
Two
</label>
<label class="selectit">
<input type="checkbox" name="three" id="three" checked>
Three
</label>
</div>

我只想为选中的输入显示标签标签并为其他人隐藏标签。

类似于 show() 用于选中的输入标签和 hide() 用于未选中的标签。

工作代码示例:

<style>.selectit{display:none;}</style>
<div id="foo">
<label class="selectit" style="display:block">
<input type="checkbox" name="one" id="one" checked>
One
</label>
<label class="selectit">
<input type="checkbox" name="two" id="two">
Two
</label>
<label class="selectit" style="display:block">
<input type="checkbox" name="three" id="three" checked>
Three
</label>
</div>

或者也许,创建一个新的 div 并只显示该 div 中选中标签的文本。

<style>.selectit{display:none;}</style>
<div id="foo">
<label class="selectit">
<input type="checkbox" name="one" id="one" checked>
One
</label>
<label class="selectit">
<input type="checkbox" name="two" id="two">
Two
</label>
<label class="selectit">
<input type="checkbox" name="three" id="three" checked>
Three
</label>
</div>
<div id="output">One - Three</div>

这甚至可能吗?还是我需要通过附加一个搜索整个复选框的 div 来做到这一点?感谢您提供任何帮助,因为我已经用尽了所有选择,而且我没有想法。提前谢谢你。

【问题讨论】:

  • 我会构建一个引用每个选中复选框的对象,以及一个引用每个标签的对象。然后我会浏览标签列表,看看for 属性是否匹配任何选中的复选框。另外,添加for 属性。这对可访问性有好处。

标签: javascript jquery html forms input


【解决方案1】:

您可以使用filter 方法过滤选中的复选框。

$('#foo input[type=checkbox]').filter(function(){
      return this.checked;
}).prev('label').show();

【讨论】:

    【解决方案2】:

    免责声明:此答案仅基于您的标题问题


    我会选择纯 CSS。喜欢

    label {
        display: none;
    } 
    
    input:checked + label {
        display: block;
    } 
    

    您只需要稍微调整一下标记即可。

    示例:http://jsfiddle.net/ZpmGd/

    【讨论】:

    • 这很简洁,我可以看到标签正确嵌套时有效。但是我正在编辑一个插件,我真的不知道编辑插件制造商的原始标记。我希望我可以使用纯 CSS 来做到这一点,因为这很好用,我只是后悔使用 jQuery。虽然 jQuery 方法目前对我来说似乎是最简单的。感谢答案。
    猜你喜欢
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多