简体   繁体   English

如何替换$(document).ready函数?

[英]How to replace $(document).ready function?

I got a problem and dont know how to fix it. 我遇到问题,不知道如何解决。 A have the following js script: 一个具有以下js脚本:

$(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. 有时,我遇到的情况是文档准备就绪,而我的部分视图中没有任何.alert类。 So, how to rewrite the function to execute it after my partial view is updated with valid .alert ? 因此,在使用有效的.alert更新我的局部视图之后,如何重写函数以执行该函数?

You either need to wait around for $(",alert") to exist first, or you need to add your code inside the loading processing. 您要么需要等待$(",alert")首先存在,要么需要在加载过程中添加代码。

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. 如果您不想紧密耦合JS文件,则可以广播另一个脚本的“面板加载”事件,该事件在文档级别捕获。

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. 如果您重新加载部分视图,我想最好的办法是将您的代码放在.ajaxComplete()函数中。

It will be ready rigth after your ajax request done. 在您的ajax请求完成后,它将准备就绪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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