这是“
Js file not loaded after partial view is refreshed”的分支问题.
问题是如果我把我的脚本放到主视图中它不能部分工作.
我的自定义脚本:
问题是如果我把我的脚本放到主视图中它不能部分工作.
我的自定义脚本:
$(function() {
$.ajaxSetup({ cache: false });
var timer = window.setTimeout(function () {
$(".alert").fadeto(1000).slideUp(1000,function () {
$(this).hide();
});
},3000);
$("[data-hide]").on("click",function () {
if (timer != null) {
clearTimeout(timer);
$(this).closest("." + $(this).attr("data-hide")).hide();
}
});
});
Photo部分视图,我需要使用我的脚本:
<div class="well">
<h3>
<strong>@Model.Name</strong>
<span class="pull-right label label-primary">@Model.AverageRaiting.ToString("# stars")</span>
</h3>
<span class="lead">@Model.Description</span>
@Html.DialogFormlink("Update",Url.Action("UpdatePhoto",new {id = @Model.PhotoId}),"Update Photo",Url.Action("Photo"))
@Html.Action("InitializeAlerts")
</div>
并且部分视图“_Alert”渲染到我需要使用上面脚本的部分:
@{
var alerts = TempData.ContainsKey(Alert.TempDataKey)
? (List<Alert>)TempData[Alert.TempDataKey]
: new List<Alert>();
if (alerts.Any())
{
<hr />
}
foreach (var alert in alerts)
{
var dismissableClass = alert.dismissable? "alert-dismissable" : null;
<div class="alert alert-@alert.AlertStyle fade in @dismissableClass">
@if (alert.dismissable)
{
<button type="button" class="close" aria-label="close" data-hide="alert">×</button>
}
@Html.Raw(alert.Message)
</div>
}
}
解决方法
使用委托事件处理程序:
$(document).on('click',"[data-hide]",function ()
jQuery选择器仅在事件时运行,因此它将使用动态添加的元素.
它通过在不变的祖先元素上侦听事件来工作(如果没有其他更接近/方便的话,文档是最安全的默认值).然后它将选择器应用于气泡链中的元素.然后,它将您的事件处理函数仅应用于导致该事件的匹配元素.
与将事件处理程序连接到单个元素相比,这非常有效,并且任何速度差异都可以忽略不计,因为您无法快速点击以通知:)