简体   繁体   中英

How to replace $(document).ready function?

I got a problem and dont know how to fix it. A have the following js script:

$(function () {
    $.ajaxSetup({ cache: false });
        var timer = window.setTimeout(function () {
        $(".alert").fadeTo(1000).slideUp(1000, function () {
            $(this).hide();
        });
    }, 3000);
    $(document).on("click", "[data-hide]", 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")//When this action is executing the document was already ready (by the first time when full page was loading), so I have no chanse to catch any .alerts in js alert file after updating this partial for another one.
</div>

Sometimes I have a situation when document is ready ealier than I have any .alert classes im my partial view. So, how to rewrite the function to execute it after my partial view is updated with valid .alert ?

You either need to wait around for $(",alert") to exist first, or you need to add your code inside the loading processing.

If you do not wish to couple your JS files tightly, you can broadcast a "panel loaded" event from the other script, which you catch at the document level.

eg

$.ajax({...}).done(function(loadedhtml){
    $somepanel.html(loadedhtml);
    $(document).trigger("panelloaded", $somepanel);
});

and listen for the generic "panel loaded" event in your main:

eg

$(document).on('panelloaded', function(panel){
    // Do stuff here to the newly loaded panel
});

If you reload your Partial View i suppose the best thing is to place your code in .ajaxComplete() function.

It will be ready rigth after your ajax request done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM