use*_*229 6 javascript asp.net-mvc jquery
这是" 刷新部分视图后未加载Js文件 "的分支问题.问题是如果我把我的脚本放到主视图中它不能部分工作.我的自定义脚本:
$(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();
}
});
});
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
并且部分视图"_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>
}
}
Run Code Online (Sandbox Code Playgroud)
使用委托事件处理程序:
$(document).on('click', "[data-hide]", function ()
Run Code Online (Sandbox Code Playgroud)
jQuery选择器仅在事件时运行,因此它将使用动态添加的元素.
它通过在不变的祖先元素上侦听事件来工作(如果没有其他更接近/方便的话,文档是最安全的默认值).然后它将选择器应用于气泡链中的元素.然后,它将您的事件处理函数仅应用于导致该事件的匹配元素.
与将事件处理程序连接到单个元素相比,这非常有效,并且任何速度差异都可以忽略不计,因为您无法快速点击以通知:)