JS文件没有'刷新后无法在局部视图中工作

The JS file doesn't work in partial view after it refreshed

本文关键字:局部 视图 工作 刷新 文件 JS      更新时间:2023-09-26

这是"刷新部分视图后未加载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();
        }
    });
});

我需要使用脚本的照片部分视图:

<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>

和partail视图"_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">&times;</button>
            }
            @Html.Raw(alert.Message)
        </div>
    }
}

使用委托的事件处理程序:

$(document).on('click', "[data-hide]", function () 

jQuery选择器仅在事件时运行因此它将使用动态添加的元素。

它通过在一个不变的祖先元素上侦听事件来工作(如果没有其他更接近/方便的东西,文档是最安全的默认值)。然后,它将选择器应用于气泡链中的元素。然后,它将事件处理程序函数仅应用于导致事件的匹配元素。

与将事件处理程序连接到单个元素相比,这是非常有效的,并且任何速度差异都可以忽略不计,因为您根本无法快速单击以注意到:)

当您删除了jQuery将其事件附加到的DOM元素时,就会发生这种情况。当您添加新元素时,jQuery不会跟踪页面并添加新事件,这是一次性的。您可以通过将事件放置在页面上始终存在的父级上,然后使用选择器来获取所需的元素来解决此问题。.on()方法的jQuery文档告诉您更多信息。

我需要修改代码如下:(如果部分视图刷新,工作良好)

var item_to_delete;
    $("#serviceCharge").on('click','.deleteItem' ,function (e) {
        item_to_delete = $(this).data('id');
        alert(item_to_delete);
    });

我以前的代码是:(工作直到部分视图不刷新)

var item_to_delete;
        $(".deleteItem").click(function (e) {
            item_to_delete = $(this).data('id');
        });