javascript - 使用 Jquery 根据复选框选择更高效地添加和删除类

标签 javascript jquery css asp.net-mvc

将 .NET MVC 与具有 14 列表的 View 一起使用。我允许用户打开模式并选择/取消选择复选框以隐藏和取消隐藏这些列。但是代码很笨重,感觉效率低下。但是它确实有效,我只是在寻求有关如何使这件事变得更好的答案。

我的做法是这样标记 TH

  <th id="col1" class="toggleMe1">
         UW
    </th>
    <th class="toggleMe2">
       @Html.DisplayNameFor(model => model.Client)
     </th>

对于 TH 和 TD 等等

<td class="toggleMe1">
     @Html.DisplayFor(modelItem => item.NameOf)
</td>
<td class="toggleMe2">
     @Html.DisplayFor(modelItem => item.Client)
 </td>

这是我使用的 Jquery。为了让我单独隔离这些列,而不关闭/打开其他列,我必须以这种方式隔离它们。 ColorMe 类有一个 display:none;属性(property)。就是这样。

if ($("#col1Off").is(":checked")){
       $('.toggleMe1').addClass("ColorMe");
  } else {
       $('.toggleMe1').removeClass("ColorMe");
  }
  if ($("#col2Off").is(":checked")) {
        $('.toggleMe2').addClass("ColorMe");
  } else {
    $('.toggleMe2').removeClass("ColorMe");
  }

我必须对所有 14 列都执行此操作。有什么办法可以缩短它吗?更有效率一些?

编辑。代码片段。

用于保存复选框的模式。在 div class="Modal-body"中查找它们。现在只有两个

<!-- Button trigger modal -->
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
            Launch demo modal
        </button>

        <!-- Modal -->
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <input type="checkbox" id="col1Off"  data-chclass="toggleMe1" />
                        <label for="col1">Uw</label>
                        <input type="checkbox" id="col2Off"  data-chclass="toggleMe2" />
                        <label for="col2">Client</label>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>

用于打开 MODAL 的代码和用于切换隐藏/取消隐藏类的代码。

$('#exampleModal').on('hide.bs.modal', function (e) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var recipient = button.data('whatever') // Extract info from data-* attributes

    $('input[type=checkbox]').change(function () {
        var el = $(this).data('chclass');
        $('.' + el).toggleClass("ColorMe");
    });


    // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
    // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
    var modal = $(this)
    modal.find('.modal-title').text('Hide or Unhide Columns')
    modal.find('.modal-body input').val(recipient)
})

其中大部分可能都不需要。我只是在测试一个模式并复制示例代码进行测试。

我必须打开它两次才能使切换类工作

最佳答案

编辑:您需要在 $(document).ready() 中设置输入更改事件,以便在 DOM 准备就绪后对其进行初始化。目前,更改监听器已添加到模态的 hide.bs.modal 上事件。 请参阅下面的代码。

$(function() {
  $('input[type=checkbox]').change(function() {
    var el = $(this).data('chclass');
    $('.' + el).toggleClass("ColorMe");
  });
})

$('#exampleModal').on('hide.bs.modal', function(e) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('Hide or Unhide Columns')
  modal.find('.modal-body input').val(recipient)
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
            Launch demo modal
        </button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
      </div>
      <div class="modal-body">
        <input type="checkbox" id="col1Off" data-chclass="toggleMe1" />
        <label for="col1">Uw</label>
        <input type="checkbox" id="col2Off" data-chclass="toggleMe2" />
        <label for="col2">Client</label>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

添加数据属性,例如。 data-chclass包含 <th> 类的每个复选框标签。

例如:<input type="checkbox" data-chclass="toggleMe1" />

然后你可以使用:

$('input[type=checkbox]').change(function() {
    var el = $(this).data('chclass');
    $('.' + el).toggleClass("ColorMe");     
});

关于javascript - 使用 Jquery 根据复选框选择更高效地添加和删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54948189/

相关文章:

javascript - 如何使用 .include() 方法检查数组内 json 中的值

javascript - 如果没有返回JSON数据则AJAX成功函数

javascript - 如何使用 jquery 处理 google recapcha?

javascript - Codeigniter Jquery Ajax,无法将数据从 Controller 访问回html表单

html - 页脚背景颜色占据了我的整个网页

html - css table td 三重对 Angular 分割

javascript - 如何使用类选择器根据其同级选择的更改事件更新标签

javascript - 需要结合 jquery 函数的帮助

javascript - 使用 javascript 隐藏/显示 css div - 隐藏后不再显示 -

javascript - $.post 验证表单字段并在出现错误时阻止提交