我有一個函數,它是一個JQuery事件處理程序。因爲它是一個JQuery事件處理程序,所以它使用this
變量來引用它所調用的對象(對於該庫來說是正常的)。如何在Javascript中重新定義`this`?
不幸的是,我現在需要手動調用該方法。如何讓被調用函數內部的this
表現得像從JQuery調用一樣?
示例代碼:
function performAjaxRequest() {
//Function which builds AJAX request in terms of "this"
}
function buildForm(dialogOfForm) {
var inputItem;
dialogOfForm.html('...');
dialogOfForm.dialog('option', 'buttons', {
"Ok" : performAjaxRequest
});
inputItem = dialogOfForm.children(':not(label)');
//Redirect enter to submit the form
inputItem.keypress(function (e) {
if (e.which === 13) {
performAjaxRequest(); //Note that 'this' isn't the dialog box
//as performAjaxRequest expects here, it's
//the input element where the user pressed
//enter!
}
}
}
比方說,我沒有一個方便的參考事件將被觸發的實際事件或元素。 – 2010-10-13 01:17:53
@Billy ...所以你想在一個變量對象或一組對象上觸發一個變量事件?如果是這樣,通用代碼是什麼樣的?什麼*做*你知道此刻你想觸發什麼,你需要觸發? – 2010-10-13 01:21:03
剛剛更新了問題 - 讓我知道如果這使得它更清晰。 – 2010-10-13 01:23:44