簡體   English   中英

在ajax內部運行函數成功回調

[英]Run a function inside ajax success call back

我創建了一個代碼段,該代碼段可檢查div中的所有圖像並根據其大小添加一個類。

我目前已經在文檔上准備好了,加載頁面時我可以很好地工作。

但是,我正在制作一個CMS,您可以在其中編輯頁面本身上的文本,然后通過ajax更新文本。

呼叫響應通常如下所示:

success: function (response) {
    if (response.databaseSuccess) {
        $("#container #" +response.postid).load("#container #" +response.postContentID);
        $targetForm.find(".saveupdatebutton").qtip("hide");
    }
}

此后,不會調整通過.load()函數加載的div中的圖像的大小。

我嘗試將我使用的代碼放入成功響應中,但沒有運氣。

響應后我應該如何調用代碼?

這是代碼:

$(document).ready(function () {
// check each image in the .blogtest divs for their width. If its less than X make it full size, if not its poor and keep it normal
var box = $(".blogtest");
box.find("img.buildimage").on('load', function () {
    var img = $(this),
        width = img.width();
    if (width >= 650) {
        img.addClass("buildimage-large");
    } else if (width < 500 && width > 101) {
        img.addClass("buildimage-small");
    }
    // if image is less than X, its most likely a smiley
    else if (width < 100) {
        img.addClass("buildimage-smiley");
    }
    }).filter(function () {
        //if the image is already loaded manually trigger the event
        return this.complete;
    }).trigger('load');
});

根據所使用的jQuery版本,您可以像這樣將.on更改為.live

box.find("img.buildimage").live('load', function () {

如果那不起作用,那么您可以嘗試以下操作。 然后,您必須按以下“正確”方式進行操作:

首先將您的函數外部化以調整圖像大小:

$(document).ready(function () {
    // check each image in the .blogtest divs for their width. If its less than X make it full size, if not its poor and keep it normal
    var box = $(".blogtest");
    box.find("img.buildimage").on('load', imageOnload)
        .filter(function () {
            //if the image is already loaded manually trigger the event
            return this.complete;
        })
        .trigger('load');
});

function imageOnload(evt){
    var img = $(evt.currentTarget),
        width = img.width();
    if (width >= 650) {
        img.addClass("buildimage-large");
    } else if (width < 500 && width > 101) {
        img.addClass("buildimage-small");
    }
    // if image is less than X, its most likely a smiley
    else if (width < 100) {
        img.addClass("buildimage-smiley");
    }
}

然后,您可以在成功回調中添加以下語句:

$("#container #" +response.postid).on("load", imageOnload);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM