亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在html表格中正確定義$(this)

如何在html表格中正確定義$(this)

慕俠2389804 2023-10-17 20:01:06
當我應用each方法時,我對定義感到困惑this。當我單擊 element 時,我想獲取每個單元格id,但似乎this顯示整個單元格calendar我的問題是① 為什么點擊單元格時this會顯示?#calendarid②單擊單元格時如何定義和獲取每個單元格?如果有人遇到過同樣的問題,請告訴我。謝謝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>
查看完整描述

2 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

each在 上應用#calendar,它會將處理程序應用于該對象,因此this將始終引用它。

相反,您需要應用eachon.day來迭代單元格和綁定處理程序。

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

function register() {

  function clicked() {

    alert("clicked");

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


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

    console.log("clickedID", clickedID);

  }


  $(this).on({

    click: clicked

  });

}

$("#calendar .day").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>


查看完整回答
反對 回復 2023-10-17
?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

this指的是日歷。刪除this并添加td.


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);

  }

  console.log(this) 

  $('td').on({  //===========> Add td instead of this

    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>


查看完整回答
反對 回復 2023-10-17
  • 2 回答
  • 0 關注
  • 151 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號