如何在html表格中正确定义$(this)

当我应用each方法时,我对定义感到困惑this。


当我单击 element 时,我想获取每个单元格id,但似乎this显示整个单元格calendar


我的问题是


① 为什么点击单元格时this会显示?#calendar


id②单击单元格时如何定义和获取每个单元格?


如果有人遇到过同样的问题,请告诉我。


谢谢


var $ = jQuery;

const $days = $(this).find('.day');


function register() {

  function clicked() {

    alert("clicked");

    $(this).toggleClass('is-clicked');

    

    let clickedID=$(this).attr('id');

    console.log("clickedID",clickedID);

  }


  $(this).on({

    click: clicked

  });

}

$("#calendar").each(register);

td {

  padding: 10px;

  border: solid black 1px;

}


table {

  border-collapse: collapse;

}


.is-clicked {

  background-color: aqua;

}


td:hover {

  background-color: yellow;

}

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>


<div id=calendar>

  <table>

    <tr>

      <td id=1 class=day>1</td>

      <td id=2 class=day>2</td>

      <td id=3 class=day>3</td>

    </tr>

  </table>

</div>


慕侠2389804
浏览 97回答 2
2回答

jeck猫

您each在 上应用#calendar,它会将处理程序应用于该对象,因此this将始终引用它。相反,您需要应用eachon.day来迭代单元格和绑定处理程序。$("#calendar&nbsp;.day").each(register);function register() {&nbsp; function clicked() {&nbsp; &nbsp; alert("clicked");&nbsp; &nbsp; $(this).toggleClass('is-clicked');&nbsp; &nbsp; let clickedID = $(this).attr('id');&nbsp; &nbsp; console.log("clickedID", clickedID);&nbsp; }&nbsp; $(this).on({&nbsp; &nbsp; click: clicked&nbsp; });}$("#calendar .day").each(register);td {&nbsp; padding: 10px;&nbsp; border: solid black 1px;}table {&nbsp; border-collapse: collapse;}.is-clicked {&nbsp; background-color: aqua;}td:hover {&nbsp; background-color: yellow;}<script src="https://code.jquery.com/jquery-3.3.1.js"></script><div id=calendar>&nbsp; <table>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td id=1 class=day>1</td>&nbsp; &nbsp; &nbsp; <td id=2 class=day>2</td>&nbsp; &nbsp; &nbsp; <td id=3 class=day>3</td>&nbsp; &nbsp; </tr>&nbsp; </table></div>

哆啦的时光机

this指的是日历。删除this并添加td.var $ = jQuery;const $days = $(this).find('.day');function register() {&nbsp; function clicked() {&nbsp; &nbsp; alert("clicked");&nbsp; &nbsp; $(this).toggleClass('is-clicked');&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; let clickedID=$(this).attr('id');&nbsp; &nbsp; console.log("clickedID",clickedID);&nbsp; }&nbsp; console.log(this)&nbsp;&nbsp; $('td').on({&nbsp; //===========> Add td instead of this&nbsp; &nbsp; click: clicked&nbsp; });}$("#calendar").each(register);td {&nbsp; padding: 10px;&nbsp; border: solid black 1px;}table {&nbsp; border-collapse: collapse;}.is-clicked {&nbsp; background-color: aqua;}td:hover {&nbsp; background-color: yellow;}<script src="https://code.jquery.com/jquery-3.3.1.js"></script><div id=calendar>&nbsp; <table>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; <td id=1 class=day>1</td>&nbsp; &nbsp; &nbsp; <td id=2 class=day>2</td>&nbsp; &nbsp; &nbsp; <td id=3 class=day>3</td>&nbsp; &nbsp; </tr>&nbsp; </table></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5