javascript 如何获取触发函数的事件源?

2015-06-08 01:03:57 +08:00
 wd0g

<html>
<body>
<div>
<input type="text" name="time" id="time" />
<input type="button" value="开始" onclick="startime()" id="button"/>
</div>
<script type="text/javascript">
function startime(){
console.debug(this);
}
</script>
</body>
</html>

如何才能获取
<input type="button" value="开始" onclick="startime()" id="button"/>

这个事件源?

3991 次点击
所在节点    JavaScript
7 条回复
Septembers
2015-06-08 01:06:22 +08:00
HTML: <input type="button" value="开始" onclick="startTime(this)" id="button"/>
JavaScript: function startTime(element) { console.log(element); }
w88975
2015-06-08 01:08:05 +08:00
onclick="startTime(event)"

function startTime(event)

一个event搞定一切
yyfearth
2015-06-08 03:38:27 +08:00
现在了 压根不该这样写
绑定事件应该用js来绑定 而不是写在html里面
至少用
document.getElementById('button').onclick = function startime(e){
console.debug(this, e);
}

一般来说最好用library比如jQuery或者类似
$('#button').click(function startime(e){
console.debug(this, e);
});
或者原生的
document.getElementById('button').addEventListener('click', function startime(e){
console.debug(this, e);
}, false);
flowfire
2015-06-08 09:24:49 +08:00
要么使用监听函数。
要么用call
onclick = startTime.call(this, a,b,c)
function starttime(a,b,c){}
sujin190
2015-06-08 09:36:36 +08:00
其实你在chrome控制台调试下,看下调用栈和各作用域变量就知道了
wd0g
2015-06-08 10:03:09 +08:00
@yyfearth 感谢,原来是我想错了~~
coolzjy
2015-06-08 10:12:46 +08:00
难道不是 event.target?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/196805

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX