【问题标题】:How to edit check/uncheck of input如何编辑检查/取消检查输入
【发布时间】:2015-10-30 10:10:58
【问题描述】:
  • 如果用户单击以跨越文本 First,它应该标记复选框 #First 等。
  • 如果用户再次点击这个范围,它应该取消选中这个复选框
  • 如果选中 input Second,则带有文本 second 的 span 必须有 class active

我该怎么做?

$("span").on("click", function() {
    $("input").prop( "checked", true );
});

CODEPEN

【问题讨论】:

  • 使用label有什么问题???

标签: jquery edit elements


【解决方案1】:

使用索引选择input

$("span").on("click", function() {
    $("input").eq($(this).index()).prop( "checked", true );
});

注意:为了防止选择所有跨度设置一些类并将其用作选择器。

【讨论】:

  • 想法是这样,但页面可以包含更多跨度和输入
【解决方案2】:

您在 Codepen 中所做的一切都在正确的轨道上。

但是,您需要以两种方式执行相同的操作。即在跨度单击时,更改复选框状态;并且在复选框更改时,切换跨度类。

另外,请记住,在使用 .eq($(this).index().. 时不要忘记传递选择器。否则,它将获得该元素相对于兄弟元素的索引。

演示小提琴:http://jsfiddle.net/abhitalks/r8w38jr5/2/

片段:

$("span.lbl").on("click", function() {
    var inp = $("input[type=checkbox]").eq($(this).index('.lbl')), 
        chk = inp.prop('checked');
    inp.prop("checked", !chk);
    $(this).toggleClass('active');
});
$("input[type=checkbox]").on("change", function() {
    var spn = $("span.lbl").eq($(this).index('[type=checkbox]')); 
    spn.toggleClass('active');
});
span {
    padding: 5px 10px; display: inline-block;
    border: 1px solid black; border-radius: 5px;
    cursor: pointer;
}
div  { margin-top: 50px; }
.active { background: black; color: white; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="lbl">First</span><span class="lbl">Second</span><span class="lbl">Third</span>
<div>
  <input type="checkbox" id="First" /><label for="First">First</label>
  <input type="checkbox" id="Second" /><label for="Second">Second</label>
  <input type="checkbox" id="Third" /><label for="Third">Third</label>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2013-11-13
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多