2012-05-27 53 views
3

我目前使用addEventListenerselect如何從事件中獲取原始元素?

<select> 
    <option value="Apple">Mac</option> 
    <option value="Microsoft">Windows</option> 
</select> 

document.querySelector("select").addEventListener("change",function(ev){ 
    //do something here... 
}, false); 

但我無法弄清楚如何從event得到原始元素。

PS:我不想這樣做:

<select onchange="func(event,this)"> 

這隻會搞亂了HTML ...

回答

2

導致該事件在事件自動分配給this元素處理程序。它也在傳遞給addEventListener()回調的事件數據結構中,在您的示例中爲ev.target

document.querySelector("select").addEventListener("change",function(ev){ 
    //do something here... 
    // you can use the value of this to access the object that 
    // is responding to the event 
    // you can also look in the event data structure for 
    // other items like ev.target 
}, false); 

您可以看到事件對象here的所有成員。

+0

非常感謝!哇...我沒有想到我可以在那裏使用'this' ... –

相關問題