我目前在 select
上使用 addEventListener
:
<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...
最佳答案
引起事件的元素会自动分配给事件处理程序中的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 .
关于javascript - 如何从事件中获取原始元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10771681/