Reputation: 5299
When I apply each
method,I confused to define this
.
When I click element , I would like to get each cells id
but it seems that this
show entire calendar
my question is
① Why this
show #calendar
when I click cells ?
② How to define and get each id
when I click cells?
If someone has experienced same problem, please let me know.
Thanks
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>
Upvotes: 1
Views: 42
Reputation: 2292
this
is referring to the calender. Remove this
and add 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>
Upvotes: 1
Reputation: 115222
You sre spplying each
on the #calendar
and it wil apply handler to that so this
would refers to it always.
Instead you need to apply each
on .day
to iterate over cells and binding handler.
$("#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>
Upvotes: 3