【发布时间】:2019-03-01 15:58:39
【问题描述】:
将 .NET MVC 与具有 14 列表的视图一起使用。我允许用户打开模式并选择/取消选择复选框以隐藏和取消隐藏这些列。但是代码很庞大,感觉效率低下。但是它确实有效,我只是在寻找如何使这件事变得更好的答案。
我这样做的方式是这样标记 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;财产。而已。
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">×</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)
})
其中大部分可能不需要。我只是在测试一个模态并复制示例代码进行测试。
我必须打开它两次才能使切换类工作
【问题讨论】:
-
你可以使用jquery函数toggleClass("ColorMe"),它可以让你简化代码api.jquery.com/toggleclass
-
jquery 实际上有显示、隐藏和切换功能,如果您只关心可见性,您可以使用这些功能
-
是的。能见度是我所关心的。但是,我已经尝试过切换类,但我似乎看不到如何像这样单独隔离它们。它适用于所有或无。有什么你想展示的例子吗?
标签: javascript jquery css asp.net-mvc