【问题标题】:JQuery: Changing style of element when Checkbox is clickJQuery:单击复选框时更改元素的样式
【发布时间】:2012-07-04 01:44:31
【问题描述】:

我有一个 html 元素(使用 MVC3 Razor)

       <h2 class="price">
              @Html.LabelFor(vm => vm.Price)
              @Html.Encode(@Model.Price)
       </h2>
        <div id="checkbox-price">
              @Html.CheckBoxFor(vm => vm.IncludeToPayment) Include in payment.
        </div>

当用户使用 JQUery 取消选中/选中 Checkbox 时,如何更改 h2 元素的样式(在这种情况下,我想要 text-decoration: line-through 里面的项目)?

提前致谢。

【问题讨论】:

    标签: jquery checkboxfor


    【解决方案1】:
    $('#checkbox-price input:checkbox').change(function(){
      if (!$(this).is(':checked')) {
         $('.price').css('text-decoration', 'line-through')
      } else {
         $('.price').css('text-decoration', 'none')
      }
    })
    

      $('#checkbox-price input:checkbox').change(function() { 
                // or $(`input[type="checkbox"]')
                var $obj = $('.price');
                if (!$(this).is(':checked')) {
                  $obj.css('text-decoration', 'line-through'); //or addClass                
                } else {
                  $obj.css('text-decoration', 'none'); // or addClass                
                }
            })
    

    【讨论】:

    • 如果我有很多复选框呢?如果我选中其他复选框,这也会触发吗?对不起,我是 JQuery 的初学者
    • @cshaplinc 在这种情况下代码应该被修改,这取决于标记的结构。
    • @undefined ++1 表示速度:P,可以做一点小改进。
    【解决方案2】:

    这是一个简单的代码和live demo

    这适用于所有复选框

    $('input[type="checkbox"]').click(function() {
        if (this.checked) {
            //alert('Checked');
            $("h2").addClass('newclass');
        } else {
            //alert('Unchecked');
            $("h2").removeClass('newclass');
        }
    });​
    

    如果您想申请特定的复选框,请使用下方

    $('input[type="checkbox"]') to $('input.someclass)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 2017-10-09
      • 1970-01-01
      相关资源
      最近更新 更多