2013-10-09 26 views
0

在事件偵聽器中,我需要對作爲事件源的元素的引用。我如何獲得?如何獲得對事件源元素的引用

對於一段時間都在使用JavaScript的人來說,這應該是一個不容忽視的工具。

包括事件處理函數在內的所有函數都在全局範圍內,因此隱含地構成DOM對象的一部分。

function WireHandlers() { 
    $('.updateResourceImageButton').click(UpdateResourceLinkClickedHandler); 
} 

function UpdateResourceLinkClickedHandler() { 
    // I would like a reference to the hyperlink/anchor 
    // that was actually clicked, i.e. the hyperlink that 
    // was the source of this event 

    // would the keyword 'this' evaluate to the element I need? 
    // or will it evaluate to the HTML DOM 'window' object 
    // in this context? 
} 

$(document).ready(function() { WireHandlers(); }); 
+2

_ 「關鍵字'this'會評估我需要的元素嗎?」_你爲什麼不測試它?是的,'this'是指被點擊的元素。 – undefined

+1

你有沒有看到'console.log(this)'是什麼? – epascarello

+0

@undefined我會有,除了有時,問更方便,尤其是。如果你對構成語言生態系統的工具/支持有點不舒服。如果我自己嘗試過,這會花費比我從你們那裏收到答案更多的時間,這會打斷我的思路。作爲一名程序員,你知道可能會有多昂貴。 –

回答

1

我認爲你可以做這樣的

$(this) 

也這是來自jQuery的文檔

var target = $(event.target); 

http://api.jquery.com/event.target/這個頁面,看一下這篇文章的詳細信息http://www.pkshiu.com/loft/archive/2009/01/understanding-this-this-and-event-in-a-jquery-callback-function

+0

非常感謝。 –

+0

@ WaterCoolerv2:不用客氣,如果這個答案是你需要的,你可以把它標記爲真正的答案 – ahmedsafan86

+0

當然可以。在我可以標記答案之前,我必須等待一段時間。 :-) –

2

當您通過引用傳遞函數時,仍然可以正常訪問參數。作爲這樣event.targetthis將是UpdateResourceLinkClickedHandler函數內的點擊的元素:

function UpdateResourceLinkClickedHandler(e) { 
    // clicked element as a native DOM element 
    var foo = e.target; 
    var bar = this; 

    // jQuery object containing clicked element 
    var $foo = $(this); 
} 

注意,在這個例子將包含相同的值既foobar

+0

非常感謝。 –