2010-03-10 49 views
1

遇到麻煩指事件對象在一個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文檔:「事件對象保證傳遞給事件處理程序。」我的問題是:如果我沒有明確地通過它,它在哪裏? ;)?

回答

1

相反的:

alert($(this).src); 

嘗試:

alert(this.src); 

$(this)是一個jQuery對象。 this是一個DOM元素。

+0

沒有工作 - 仍然返回undefined。 :(由於jQuery正在調用函數,並且(可能)傳遞參數,比如哪個對象觸發了該函數,爲什麼jQuery對象不會有意義? – Summer 2010-03-10 21:18:11

+0

@Summer - 因爲src'不是jQuery對象的屬性。如果你真的想在這個上下文中包裝'this'(這是引發該事件的元素),那麼你可以使用'$(this).attr('src')'來獲得' src'屬性,這是很多不必要的包裝和函數調用,儘管如此, – 2010-03-10 21:44:57

+0

Aha。謝謝你的解釋。 – Summer 2010-03-10 21:57:28

2
$('.arrow').bind('click',function(event){ update_support(event);}); 

未經測試,但應通過參考事件update_support

編輯:你想也需要修改update_support,明明:

function update_support(evt) { 
    alert(evt.target.src); 
} 
+0

可以工作,但它看起來像OP想''update_support()''中的'event.target'函數,因爲他們希望獲得用於編輯的'src'屬性 – 2010-03-10 21:14:26

+0

+1,儘管包裝'update_support'的匿名函數不是必需的 - 事件對象將作爲第一個參數傳遞給它,函數中需要一個參數簽名以捕獲價值 – 2010-03-10 21:20:07

+0

好吧,你可以像使用'arguments [0]'一樣使用'arguments'來引用它,但IMO會讓它更容易擁有一個捕獲參數值的參數。 – 2010-03-10 21:28:58

1

由於在這種情況下,替代雙方inkedmn的和J-P的答案

// 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(e) { 
    alert(e.target.src); 
} 

eevent對象(跨瀏覽器標準化)

如果你沒有在事件處理程序簽名的明確定義事件對象參數一個參數,事件對象可以使用arguments

// 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(arguments[0].target.src); 
} 

但在我的真實想法被引用,它將使代碼更易於閱讀通過顯式定義事件對象參數的參數。

+0

我試過這個,但是我的瀏覽器報告,當它沒有被明確地傳遞時,e是未定義的。 – Summer 2010-03-10 21:29:02

+0

當你說它沒有明確通過時,你是什麼意思?你的意思是從'update_support'函數簽名中刪除參數嗎?在這種情況下,'e'將是未定義的,因爲它沒有在任何地方定義(不包括變量'e'可以在父範圍中聲明的概念)。 – 2010-03-10 21:33:32

+0

同意。我的意思是當我不使用.bind('click',update_support(this)),而是嘗試使用.bind('click',update_support)或.bind('click',update_support(event)) - 它不會沒有工作。也許我會繼續處理這個問題,然後留下漂亮的語法。 :) – Summer 2010-03-10 21:38:13

相關問題