最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - The JS file doesn't work in partial view after it refreshed - Stack Overflow

programmeradmin2浏览0评论

This is branch question of "Js file not loaded after partial view is refreshed". The broblem is that if I put my script in to the main view it doesn't work in partial. My custom script:

$(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();
        }
    });
});

The Photo partial view where I need to use my script:

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

And partail view "_Alert" which rendering in to the partial where I need to use the script above:

@{
    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 [email protected] fade in @dismissableClass">
            @if (alert.Dismissable)
            {
                <button type="button" class="close" aria-label="close" data-hide="alert">&times;</button>
            }
            @Html.Raw(alert.Message)
        </div>
    }
}

This is branch question of "Js file not loaded after partial view is refreshed". The broblem is that if I put my script in to the main view it doesn't work in partial. My custom script:

$(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();
        }
    });
});

The Photo partial view where I need to use my script:

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

And partail view "_Alert" which rendering in to the partial where I need to use the script above:

@{
    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 [email protected] fade in @dismissableClass">
            @if (alert.Dismissable)
            {
                <button type="button" class="close" aria-label="close" data-hide="alert">&times;</button>
            }
            @Html.Raw(alert.Message)
        </div>
    }
}
Share Improve this question edited May 23, 2017 at 12:34 CommunityBot 11 silver badge asked Dec 24, 2015 at 10:20 user3818229user3818229 1,6472 gold badges22 silver badges48 bronze badges 12
  • Place the script in your main layout, not in a partial. Then use the delegated event handler shown. This should work on all partial views. – iCollect.it Ltd Commented Dec 24, 2015 at 10:42
  • @TrueBlueAussie Right now I put it in main view of partial photo. I think it is bad to load it in layout if I don't need this script in another views. – user3818229 Commented Dec 24, 2015 at 10:45
  • Once loaded the overhead is the same whether you use it or not. It is a very tiny script. Just load it in main, once, and don't make life harder for yourself :) – iCollect.it Ltd Commented Dec 24, 2015 at 10:46
  • @TrueBlueAussie thanks for good advice but could you explain why it doesn't work if I place it in the Main Photo View? – user3818229 Commented Dec 24, 2015 at 10:48
  • Sure: If you please explain what your Main Photo view is... Is it a partial, is it a full view? How is it loaded? Is it the one shown above (which is not named)? :) – iCollect.it Ltd Commented Dec 24, 2015 at 10:50
 |  Show 7 more ments

2 Answers 2

Reset to default 7

Use a delegated event handler:

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

The jQuery selector is only run at event time, so it will work with dynamically added elements.

It works by listening for the event at a non-changing ancestor element (document is the safest default if nothing else is closer/convenient). It then applies the selector to the elements in the bubble-chain. It then applies your event handler function to only the matching elements that caused the event.

This is very efficient pared to connecting event handlers to individual elements and any speed difference is negligible as you simply cannot click fast enough to notice :)

This happens as you have removed the DOM elements that jQuery attached its events to. jQuery doesn't keep track of the page and add new events when you add new elements, its a one time deal. You can get around this by placing the event on a parent that always exists on the page and then use a selector to get at the elements you want. The jQuery documentation for the .on() method tells you more.

I need to modify code as follows:(working well if partial view refreshed)

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

My Previous code was: (working till partial view not refresh)

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

评论列表(0)

  1. 暂无评论