遇到麻煩指事件對象在一個jQuery功能:如何從外部函數引用事件對象? - jQuery的
// Execute a function when an image with the arrow class is clicked
$('.arrow').bind('click',update_support);
// Function tries to refer to the calling image using $(this)
function update_support() {
alert($(this).src);
}
// Result: an alert of 'undefined'
此代碼的工作,但它明確地傳遞了「這個」對象的功能,我覺得有一定有更好的方式:
$('.arrow').bind('click',update_support(this));
function update_support(obj) {
alert(obj.src);
}
// Result: an alert with the src of the clicked image
編輯讓我更清楚的問題: 爲什麼我應該給任何參數明確的功能?來自http://api.jquery.com/category/events/event-object的jQuery文檔:「事件對象保證傳遞給事件處理程序。」我的問題是:如果我沒有明確地通過它,它在哪裏? ;)?
沒有工作 - 仍然返回undefined。 :(由於jQuery正在調用函數,並且(可能)傳遞參數,比如哪個對象觸發了該函數,爲什麼jQuery對象不會有意義? – Summer 2010-03-10 21:18:11
@Summer - 因爲src'不是jQuery對象的屬性。如果你真的想在這個上下文中包裝'this'(這是引發該事件的元素),那麼你可以使用'$(this).attr('src')'來獲得' src'屬性,這是很多不必要的包裝和函數調用,儘管如此, – 2010-03-10 21:44:57
Aha。謝謝你的解釋。 – Summer 2010-03-10 21:57:28