2013-08-18 26 views
0

這感覺就像一個業餘問題,但你怎麼參加事件在JavaScript/jQuery中的自定義函數?如何在JavaScript/jQuery中接收事件變量?

現在,我使用這個:

$(".button").on("click", function(event){ 
    removeButton(); 
}); 

function removeButton() { 
    $(this).removeClass("specifiedClass"); 
} 

我試圖讓removeButton()明白,我希望它刪除類,它是在.button本身。

我不知道如何讓removeButton()採取的事件,但我已經試過:

$(".button").on("click", function(event){ 
    removeButton(event); 
}); 

function removeButton(event) { 
    $(this).removeClass("specifiedClass"); 
} 

但它不工作。有誰知道如何?

回答

5

您需要將元素作爲參數:

$(".button").on("click", function(event){ 
    removeButton(this); 
}); 

function removeButton(elem) { 
    $(elem).removeClass("specifiedClass"); 
} 
+0

哦哇。它的工作完美。真棒!另外,它是建議把它作爲'removeButton(event)'?或者我應該把它作爲一些其他變量,以避免衝突? –

+0

你正在使用一個元素..我會讓它像元素一樣。 – Daniel

+0

@Daniel啊,我明白了。好的! –

1

SLaks的解決方案是完全可以接受的,但如果你不想改變你的removeButton功能,你可以使用call or apply與調用你的函數正確this價值:

$(".button").on("click", function(event){ 
    removeButton.call(this); 
}); 

function removeButton() { 
    $(this).removeClass("specifiedClass"); 
}