V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
wd0g
V2EX  ›  JavaScript

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

  •  
  •   wd0g · 2015-06-08 01:03:57 +08:00 · 3967 次点击
    这是一个创建于 3259 天前的主题,其中的信息可能已经有所发展或是发生改变。

    <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"/>

    这个事件源?

    7 条回复    2015-06-08 10:12:46 +08:00
    Septembers
        1
    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
        2
    w88975  
       2015-06-08 01:08:05 +08:00
    onclick="startTime(event)"

    function startTime(event)

    一个event搞定一切
    yyfearth
        3
    yyfearth  
       2015-06-08 03:38:27 +08:00   ❤️ 1
    现在了 压根不该这样写
    绑定事件应该用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
        4
    flowfire  
       2015-06-08 09:24:49 +08:00
    要么使用监听函数。
    要么用call
    onclick = startTime.call(this, a,b,c)
    function starttime(a,b,c){}
    sujin190
        5
    sujin190  
       2015-06-08 09:36:36 +08:00
    其实你在chrome控制台调试下,看下调用栈和各作用域变量就知道了
    wd0g
        6
    wd0g  
    OP
       2015-06-08 10:03:09 +08:00
    @yyfearth 感谢,原来是我想错了~~
    coolzjy
        7
    coolzjy  
       2015-06-08 10:12:46 +08:00
    难道不是 event.target?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3919 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 00:52 · PVG 08:52 · LAX 17:52 · JFK 20:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.