【发布时间】:2020-07-19 00:09:17
【问题描述】:
我有一个包含一些 JavaScript 的局部视图,这个局部视图可以在网页上多次显示。但是,当它多次显示时,JavaScript 仅适用于局部视图的第一个实例。我希望 JavaScript 只影响它自己的部分视图,所以当我更改 SourceFormSelect 时。这是我的部分视图的 HTML:
<div id="AddMedia">
<form>
<div class="container">
<div class="form-row">
<div class="col-6 dropdown my-2 px-0">
<label class="control-label">Source:<span class="text-danger ml-1">*</span></label>
<select id="SourceFromSelect" asp-for="Medias.SourceFrom" asp-items="Html.GetEnumSelectList(typeof(SourceFromEnum))" style="width:85%;" class="btn border-dark" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<option class="dropdown-item" selected>Select</option>
</select>
<span asp-validation-for="Medias.SourceFrom" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<div class="col-5">
<div id="MediaFile" class="form-group">
<label for="exampleFormControlFile1">Pick a File</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
<div id="MediaLink" class="form-group">
<label for="url">Link the Media</label>
<input type="url" class="form-control" id="exampleFormControlFile1">
</div>
</div>
</div>
</div>
</form>
</div>
这是它的脚本:
document.getElementById("mediaFile").style.display = "none";
$('#SourceFromSelect').change(function () {
var e = document.getElementById("SourceFormSelect");
var strUser = e.options[e.selectedIndex].value;
if (strUser == 6) {
document.getElementById("mediaFile").style.display = "inline-block";
document.getElementById("mediaLink").style.display = "none";
}
else {
document.getElementById("mediaFile").style.display = "none";
document.getElementById("mediaLink").style.display = "inline-block";
}
})
最后,这里是我称之为局部视图的地方:
<div id="MediaList">
@for (i = 0; i < MediaCount; ++i)
{
<partial name="_MediaPartial" />
}
</div>
【问题讨论】:
-
不要对多个项目使用 ID。考虑使用“事件委托”。
-
我对事件委托不熟悉,这里怎么用?
-
javascript.info/event-delegation 在底层 HTMl 可能发生变化时使用。
-
过去 2 个小时我一直在研究事件委托,但我无法解决我的问题。你能发布一个答案来说明如何做吗?
标签: javascript html asp.net-core razor partial-views