推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
wd0g

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

  •  
  •   wd0g · Jun 8, 2015 · 4511 views
    This topic created in 4019 days ago, the information mentioned may be changed or developed.

    <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 replies    2015-06-08 10:12:46 +08:00
    Septembers
        1
    Septembers  
       Jun 8, 2015
    HTML: <input type="button" value="开始" onclick="startTime(this)" id="button"/>
    JavaScript: function startTime(element) { console.log(element); }
    w88975
        2
    w88975  
       Jun 8, 2015
    onclick="startTime(event)"

    function startTime(event)

    一个event搞定一切
    yyfearth
        3
    yyfearth  
       Jun 8, 2015   ❤️ 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  
       Jun 8, 2015
    要么使用监听函数。
    要么用call
    onclick = startTime.call(this, a,b,c)
    function starttime(a,b,c){}
    sujin190
        5
    sujin190  
       Jun 8, 2015
    其实你在chrome控制台调试下,看下调用栈和各作用域变量就知道了
    wd0g
        6
    wd0g  
    OP
       Jun 8, 2015
    @yyfearth 感谢,原来是我想错了~~
    coolzjy
        7
    coolzjy  
       Jun 8, 2015
    难道不是 event.target?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   928 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 20:55 · PVG 04:55 · LAX 13:55 · JFK 16:55
    ♥ Do have faith in what you're doing.