当我应用each
方法时,我很困惑如何定义this
。
当我单击 element 时,我想获取每个单元格 id
但似乎 this
显示整个日历
我的问题是
① 为什么当我点击单元格时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>
最佳答案
您在#calendar
上应用each
,它会将处理程序应用于该this
,因此this
将始终引用它。
相反,您需要在 .day
上应用 each
来迭代单元格并绑定(bind)处理程序。
$("#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>
关于javascript - 如何在html表格中正确定义$(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910997/