e.target返回undefined?

时间:2016-08-24 03:11:26

标签: javascript events undefined

以下函数返回undefined而不是单击的元素的ID。为什么要这样做?

// get id of the target element that is clicked on
getId: function() {
    var cell = document.getElementById('board');
    cell.addEventListener('click', function(e) {
    return e.target.id;
    });
},

1 个答案:

答案 0 :(得分:2)

你的getId()函数只是添加一个监听器,而不是返回id ...

考虑这个片段,它正在运作:

var cell = document.getElementById('board');
var id = cell.addEventListener('click', function(e) {
  console.log (e.target.id);
});
<body>
  <div id="board">
    <div id="messageArea">Let's begin! Enter a position below. </div>
    <table>
      <tr>
        <td id="00">00</td><td id="01">01</td><td id="02">02</td><td id="03">03</td><td id="04"04>04</td><td id="05">05</td><td id="06">06</td>
      </tr>
      <tr>
        <td id="10">10</td><td id="11">11</td><td id="12">12</td><td id="13">13</td><td id="14">14</td><td id="15">15</td><td id="16">16</td>
      </tr>
      <tr>
        <td id="20">20</td><td id="21">21</td><td id="22">22</td><td id="23">23</td><td id="24">24</td><td id="25">25</td><td id="26">26</td>
      </tr>
      <tr>
        <td id="30">30</td><td id="31">31</td><td id="32">32</td><td id="33">33</td><td id="34">34</td><td id="35">35</td><td id="36">36</td>
      </tr>
      <tr>
        <td id="40">40</td><td id="41">41</td><td id="42">42</td><td id="43">43</td><td id="44">44</td><td id="45">45</td><td id="46">46</td>
      </tr>


    </table>

  </div>

  <form>
    <input type="text" id="guessInput" placeholder="A0">
    <input type="button" id="fireButton" value="Fire!">
  </form>

</body>