Reputation: 17
I have been struggling to simplify some query selectors. The best I could do is this.
$($(".NextYearDays td[data-index='1'], .NextYearDays td[data-index='2'] , .NextYearDays td[data-index='3']")).on("change", function ()
{
});
Is there a way to include the list of indexes I want without expanding the selector with same base structure?
Upvotes: 0
Views: 68
Reputation: 24638
Welcome to Stackoverflow @Comelius Scheepers! We hope you like it here.
You can use the .filter()
method as suggested by @Chris G, and use something like [list-of-indices].includes( ... )
:
$('.NextYearDays td[data-index]').filter(function() {
return [1,2,3].includes(+$(this).data('index'))
}).on('change', function() {
//event code here
});
Upvotes: 1
Reputation: 122906
Without JQuery you could use event delegation and check the index value within the event handler.
Side note: change
is not a valid event for <td>
.
const handle = evt => {
const indx = evt.target.dataset.index;
if (indx && [2,3,5].find( v => v === +indx )) {
console.clear();
console.log(`hi from ${evt.target.dataset.index}`);
}
};
document.addEventListener("click", handle);
td {cursor: pointer}
<table>
<tr>
<td data-index="1"> 1 </td>
<td data-index="2"> 2 </td>
<td data-index="3"> 3 </td>
<td data-index="4"> 4 </td>
<td data-index="5"> 5 </td>
</tr>
</table>
Upvotes: 0