将自身值传递到函数中

Passing itself value into function

本文关键字:函数 值传      更新时间:2023-09-26

我有以下内容,您可以看到我正在尝试传递函数this 这在 JavaScript''jQuery 中是否可能,如果是这样,如何?似乎找不到我认为我的术语错误的任何东西。

function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
        jQuery(".ShowPleaseWait").click(function () {
            processingReplacer("Please Wait...", this);
        });
        jQuery(".ShowProcessing").click(function () {
            processingReplacer("Processing...", this);
        });
    }
}
function processingReplacer(message, this) { 
        if (Page_IsValid) {
            jQuery(this).hide();
            jQuery(this).after("<img id='" + jQuery(this).attr('id') + "' class='" + jQuery(this).attr('class') + "' src='/content/images/processing.gif' /> " + message);
            alert("woohoo"); 
        }
}

不能使用 this 作为函数参数的名称。将其更改为其他内容:

function processingReplacer(message, target) { 
    if (Page_IsValid) {
        jQuery(target).hide();
        jQuery(target).after("<img id='" + jQuery(target).attr('id') + "' class='" +
           jQuery(target).attr('class') + "' src='/content/images/processing.gif' /> " +
           message);
        alert("woohoo"); 
    }
}

你可以这样做:

processingReplacer.call(this, "Please Wait...");

function processingReplacer(message) { 
        if (Page_IsValid) {
            jQuery(this).hide();
            jQuery(this).after("<img id='" + jQuery(this).attr('id') + "' class='" + jQuery(this).attr('class') + "' src='/content/images/processing.gif' /> " + message);
            alert("woohoo"); 
        }
}

使用调用,您可以设置this的上下文。然而,乔恩的回答可能更具可读性。