我的主页包含许多 PartialViews
这是我的 Index.cshtml
<div class="container">
@{
foreach (var summary in Model.Summaries)
{
<div class="partialViewWrapper">
@Html.Partial("_Summary", summary)
</div>
}
}
</div>
这是我的 JavaScript:
$(document).ready(function() {
$(".toggle").on("click",
function() {
var btn = $(this);
var state = btn.html();
if (state === 'Show Down Times') {
btn.html('Hide Down Times');
$('.foo').show();
} else {
btn.html('Show Down Times');
$('.foo').hide();
}
我的部分 View (相关位):
<div class="row">
<div class="col-md-12">
<button class="toggle btn btn-default" >Show Down Times</button>
</div>
<div class="foo col-md-12" style="display: none">
<table class="table table-striped table-bordered table-responsive">
...
</table>
</div>
</div>
我的问题是,当我单击第一个部分 View 上的按钮时,它会将其文本更改为“从显示中隐藏”,但两个部分 View 都显示各自的表格。
因此,更改按钮文本的 JS 被应用于正确的部分 View 按钮,但显示/隐藏表格被应用于所有部分 View 。
我认为我需要对 $(this) 做一些事情,而不仅仅是按类引用它,但我不知道如何使用 JQuery 来实现这一点。
谢谢
最佳答案
使用相对选择器获取包含两个元素的 .closest()
祖先,然后 .find()
该祖先内的另一个元素。
var btn = $(this);
var foo = btn.closest('.row').find('.foo');
if (state === 'Show Down Times') {
btn.html('Hide Down Times');
foo.show();
} else {
btn.html('Show Down Times');
foo.hide();
}
关于javascript - MVC PartialViews 和 JQuery,JS 应用于所有 PartialViews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42247693/